import {
  Body,
  Controller,
  Get,
  HttpCode,
  Param,
  ParseUUIDPipe,
  Patch,
  Post,
} from '@nestjs/common';
import {
  PreventiveGenerateSchema,
  TaskTemplateCreateSchema,
  TaskTemplateUpdateSchema,
  type PreventiveGenerate,
  type TaskTemplateCreate,
  type TaskTemplateUpdate,
} 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 { PreventiveService } from './preventive.service';

@Controller('preventive')
export class PreventiveController {
  constructor(private readonly preventive: PreventiveService) {}

  @Get('templates')
  @RequirePermission('WORK_ORDERS', 'view')
  listTemplates() {
    return this.preventive.listTemplates();
  }

  @Post('templates')
  @RequirePermission('SETTINGS', 'create')
  createTemplate(
    @Body(new ZodValidationPipe(TaskTemplateCreateSchema)) body: TaskTemplateCreate,
  ) {
    return this.preventive.createTemplate(body);
  }

  @Patch('templates/:id')
  @RequirePermission('SETTINGS', 'edit')
  updateTemplate(
    @Param('id', ParseUUIDPipe) id: string,
    @Body(new ZodValidationPipe(TaskTemplateUpdateSchema)) body: TaskTemplateUpdate,
  ) {
    return this.preventive.updateTemplate(id, body);
  }

  @Post('generate')
  @HttpCode(200) // idempotent : rien n'est « créé » de plus au second appel
  @RequirePermission('WORK_ORDERS', 'create')
  generate(
    @Body(new ZodValidationPipe(PreventiveGenerateSchema)) body: PreventiveGenerate,
    @CurrentUser() user: AuthenticatedUser,
  ) {
    return this.preventive.generate(body.month, user);
  }

  @Get('status')
  @RequirePermission('WORK_ORDERS', 'view')
  status() {
    return this.preventive.status();
  }
}
