import {
  Body,
  Controller,
  Get,
  HttpCode,
  Post,
  Query,
  Req,
  UseGuards,
} from "@nestjs/common";
import { Request } from "express";
import { Type } from "class-transformer";
import { IsBoolean, IsInt, IsOptional, IsString, Max, Min } from "class-validator";
import { AbilityGuard } from "../auth/ability.guard";
import { AuthenticatedGuard } from "../auth/authenticated.guard";
import { RequireAbility } from "../auth/require-ability.decorator";
import { RenewalsService } from "./renewals.service";

/** The pólizas half of the shared "Flags del envío" panel. Only `debug`
 *  means anything here — the day gate and the send limit are estado-de-cuenta
 *  concepts — so the other two are simply not accepted. */
class RenewalFlagsDto {
  @IsOptional()
  @IsBoolean()
  debug?: boolean;
}

class SendRenewalDto extends RenewalFlagsDto {
  @IsString()
  policyId!: string;

  /** 1 = 30 días antes, 2 = 15 días antes, 3 = 7 días después. */
  @Type(() => Number)
  @IsInt()
  @Min(1)
  @Max(3)
  generation!: number;
}

@UseGuards(AuthenticatedGuard, AbilityGuard)
@Controller("renewals")
export class RenewalsController {
  constructor(private readonly renewals: RenewalsService) {}

  @Get("pending")
  pending(@Query("days") days?: string) {
    return this.renewals.pending(
      Math.min(365, Math.max(1, Number(days) || 30)),
    );
  }

  @Post("sweep")
  @RequireAbility("renewal:send")
  sweep(@Body() dto: RenewalFlagsDto, @Req() req: Request) {
    return this.renewals.sweep((req.user as { id: string }).id, {
      debug: dto?.debug,
    });
  }

  /** Send a single pending notice from the /notificaciones list. */
  @Post("send")
  @RequireAbility("renewal:send")
  @HttpCode(200)
  send(@Body() dto: SendRenewalDto, @Req() req: Request) {
    return this.renewals.sendOne(
      dto.policyId,
      dto.generation,
      (req.user as { id: string }).id,
      { debug: dto.debug },
    );
  }
}
