import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
} from '@nestjs/common';
import {
  AssetComponentCreateSchema,
  AssetCreateSchema,
  AssetUpdateSchema,
  type AssetComponentCreate,
  type AssetCreate,
  type AssetUpdate,
} from '@siop/shared';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import { RequirePermission } from '../permissions/require-permission.decorator';
import { AssetsService } from './assets.service';

@Controller('assets')
export class AssetsController {
  constructor(private readonly assetsService: AssetsService) {}

  @Get()
  @RequirePermission('ASSETS', 'view')
  list() {
    return this.assetsService.list();
  }

  /** Avant ':id' (ordre des routes) — authentification seule : le demandeur
   *  doit pouvoir désigner l'appareil qu'il signale. */
  @Get('options')
  options() {
    return this.assetsService.options();
  }

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

  @Post()
  @RequirePermission('ASSETS', 'create')
  create(@Body(new ZodValidationPipe(AssetCreateSchema)) body: AssetCreate) {
    return this.assetsService.create(body);
  }

  @Patch(':id')
  @RequirePermission('ASSETS', 'edit')
  update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(AssetUpdateSchema)) body: AssetUpdate,
  ) {
    return this.assetsService.update(id, body);
  }

  @Post(':id/components')
  @RequirePermission('ASSETS', 'edit')
  addComponent(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(AssetComponentCreateSchema)) body: AssetComponentCreate,
  ) {
    return this.assetsService.addComponent(id, body);
  }

  @Delete(':id/components/:componentId')
  @RequirePermission('ASSETS', 'edit')
  @HttpCode(204)
  removeComponent(
    @Param('id', ParseUUIDPipe) id: string,
    @Param('componentId', ParseUUIDPipe) componentId: string,
  ) {
    return this.assetsService.removeComponent(id, componentId);
  }
}
