import {
  Body,
  Controller,
  Get,
  HttpCode,
  Param,
  ParseUUIDPipe,
  Post,
} from '@nestjs/common';
import {
  RequestApproveSchema,
  RequestCreateSchema,
  RequestRejectSchema,
  type RequestApprove,
  type RequestCreate,
  type RequestReject,
} from '@siop/shared';
import {
  AuthenticatedUser,
  CurrentUser,
} from '../auth/current-user.decorator';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { RequirePermission } from '../permissions/require-permission.decorator';
import { RequestsService } from './requests.service';

@Controller('requests')
export class RequestsController {
  constructor(private readonly requests: RequestsService) {}

  @Get()
  @RequirePermission('REQUESTS', 'view')
  list(@CurrentUser() user: AuthenticatedUser) {
    return this.requests.list(user);
  }

  @Post()
  @RequirePermission('REQUESTS', 'create')
  create(
    @Body(new ZodValidationPipe(RequestCreateSchema)) body: RequestCreate,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.requests.create(body, user);
  }

  @Post(':id/approve')
  @RequirePermission('REQUESTS', 'edit')
  approve(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(RequestApproveSchema)) body: RequestApprove,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.requests.approve(id, body, user);
  }

  @Post(':id/reject')
  @HttpCode(200) // le contrat : 200, la demande est mise à jour
  @RequirePermission('REQUESTS', 'edit')
  reject(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(RequestRejectSchema)) body: RequestReject,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.requests.reject(id, body, user);
  }
}
