import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
} from "@nestjs/common";
import { TemplatesService } from "./templates.service.js";
import {
  createTemplateSchema,
  updateTemplateSchema,
  renderTemplateSchema,
  listTemplatesSchema,
} from "./templates.dto.js";
import type {
  CreateTemplateDto,
  UpdateTemplateDto,
  RenderTemplateDto,
} from "./templates.dto.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";

/**
 * TemplatesController —— 通知模板 REST API。
 *
 * 对齐 02-architecture-design.md §4.1：
 * - GET /templates（列表）
 * - POST /templates（创建）
 * - PUT /templates/:id（更新）
 * - DELETE /templates/:id（删除）
 * - POST /templates/render（渲染）
 */
@Controller("templates")
export class TemplatesController {
  constructor(private readonly service: TemplatesService) {}

  @Get()
  @RequirePermission(Permissions.MSG_NOTIFICATION_MANAGE)
  async list(
    @Query("type") type: string,
    @Query("status") status: string,
  ): Promise<{ success: true; data: unknown }> {
    // 用 Zod schema 验证 query 参数，自动推断 NotificationType/TemplateStatus 联合类型
    const filter = listTemplatesSchema.parse({
      type: type || undefined,
      status: status || undefined,
    });
    const templates = await this.service.list(filter);
    return { success: true, data: { templates } };
  }

  @Post()
  @RequirePermission(Permissions.MSG_NOTIFICATION_MANAGE)
  async create(
    @Body() body: unknown,
  ): Promise<{ success: true; data: unknown }> {
    const dto: CreateTemplateDto = createTemplateSchema.parse(body);
    const template = await this.service.create(dto);
    return { success: true, data: template };
  }

  @Get(":id")
  @RequirePermission(Permissions.MSG_NOTIFICATION_MANAGE)
  async getById(
    @Param("id") id: string,
  ): Promise<{ success: true; data: unknown }> {
    const template = await this.service.getById(id);
    return { success: true, data: template };
  }

  @Put(":id")
  @RequirePermission(Permissions.MSG_NOTIFICATION_MANAGE)
  async update(
    @Param("id") id: string,
    @Body() body: unknown,
  ): Promise<{ success: true; data: unknown }> {
    const dto: UpdateTemplateDto = updateTemplateSchema.parse(body);
    const template = await this.service.update(id, dto);
    return { success: true, data: template };
  }

  @Delete(":id")
  @RequirePermission(Permissions.MSG_NOTIFICATION_MANAGE)
  async delete(@Param("id") id: string): Promise<{ success: true }> {
    await this.service.delete(id);
    return { success: true };
  }

  @Post("render")
  @RequirePermission(Permissions.MSG_NOTIFICATION_SEND)
  async render(
    @Body() body: unknown,
  ): Promise<{ success: true; data: unknown }> {
    const dto: RenderTemplateDto = renderTemplateSchema.parse(body);
    const rendered = await this.service.render(dto);
    return { success: true, data: rendered };
  }
}
