import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import {
  IsDateString,
  IsInt,
  IsOptional,
  IsString,
  IsUUID,
  Min,
} from 'class-validator';
import { MaintenanceService } from './maintenance.service';
import { Roles } from '../../common/decorators/roles.decorator';
import {
  CurrentUser,
  AuthenticatedUser,
} from '../../common/decorators/current-user.decorator';

class CreatePlanDto {
  @IsUUID() complexId!: string;
  @IsString() title!: string;
  @IsString() equipment!: string;
  @IsInt() @Min(1) frequencyDays!: number;
  @IsDateString() nextDueDate!: string;
  @IsOptional() @IsUUID() providerId?: string;
}

class CompleteEventDto {
  @IsOptional() @IsString() reportUrl?: string;
  @IsOptional() @IsString() notes?: string;
}

@ApiTags('maintenance')
@ApiBearerAuth()
@Controller()
export class MaintenanceController {
  constructor(private readonly service: MaintenanceService) {}

  @Post('maintenance-plans')
  @Roles('SUPERADMIN', 'SYNDIC')
  create(@CurrentUser() u: AuthenticatedUser, @Body() dto: CreatePlanDto) {
    return this.service.createPlan(u, {
      ...dto,
      nextDueDate: new Date(dto.nextDueDate),
    });
  }

  @Get('maintenance-plans')
  list(@CurrentUser() u: AuthenticatedUser, @Query('complexId') complexId?: string) {
    return this.service.listPlans(u, complexId);
  }

  @Get('maintenance-events')
  events(@CurrentUser() u: AuthenticatedUser, @Query('complexId') complexId: string) {
    return this.service.listEvents(u, complexId);
  }

  @Patch('maintenance-events/:id/complete')
  @Roles('SUPERADMIN', 'SYNDIC', 'PRESTATAIRE')
  complete(
    @CurrentUser() u: AuthenticatedUser,
    @Param('id') id: string,
    @Body() dto: CompleteEventDto,
  ) {
    return this.service.completeEvent(u, { eventId: id, ...dto });
  }

  @Post('maintenance/run-now')
  @Roles('SUPERADMIN', 'SYNDIC')
  trigger() {
    return this.service.triggerNow();
  }
}
