import {
  Body,
  Controller,
  Get,
  HttpCode,
  Param,
  ParseUUIDPipe,
  Post,
} from '@nestjs/common';
import {
  PurchaseOrderCreateSchema,
  PurchaseOrderTransitionSchema,
  type PurchaseOrderCreate,
  type PurchaseOrderTransition,
} 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 { PurchaseOrdersService } from './purchase-orders.service';

@Controller('purchase-orders')
export class PurchaseOrdersController {
  constructor(private readonly purchaseOrders: PurchaseOrdersService) {}

  @Get()
  @RequirePermission('PURCHASE_ORDERS', 'view')
  list() {
    return this.purchaseOrders.list();
  }

  @Get(':id')
  @RequirePermission('PURCHASE_ORDERS', 'view')
  get(@Param('id', ParseUUIDPipe) id: string) {
    return this.purchaseOrders.get(id);
  }

  @Post()
  @RequirePermission('PURCHASE_ORDERS', 'create')
  create(
    @Body(new ZodValidationPipe(PurchaseOrderCreateSchema)) body: PurchaseOrderCreate,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.purchaseOrders.create(body, user);
  }

  @Post(':id/transition')
  @HttpCode(200) // le contrat : 200, l'état change
  @RequirePermission('PURCHASE_ORDERS', 'edit')
  transition(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(PurchaseOrderTransitionSchema)) body: PurchaseOrderTransition,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.purchaseOrders.transition(id, body, user);
  }
}
