/**
 * 表单模板服务
 * 完全符合 API 文档规范
 */

import {
  Injectable,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { Prisma } from '@prisma/client';
import {
  CreateFormTemplateDto,
  UpdateFormTemplateDto,
  QueryFormTemplatesDto,
  CreateFormFromTemplateDto,
} from '../dto';
import { FormIdentifierResolverService } from './form-identifier-resolver.service';
import { FormDefinitionService } from './form-definition.service';

@Injectable()
export class FormTemplateService {
  private readonly logger = new Logger(FormTemplateService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly identifierResolver: FormIdentifierResolverService,
    private readonly formDefinitionService: FormDefinitionService
  ) {}

  // ============================================
  // 1. 创建表单模板
  // ============================================

  async create(dto: CreateFormTemplateDto, createdBy: string) {
    this.logger.log(`Creating form template: ${JSON.stringify(dto.nameI18n)}`);

    const template = await this.prisma.formTemplate.create({
      data: {
        nameI18n: dto.nameI18n,
        descriptionI18n: dto.descriptionI18n,
        category: dto.category,
        icon: dto.icon,
        color: dto.color,
        template: dto.template,
        isBuiltin: dto.isBuiltin,
        isPublic: dto.isPublic,
        createdBy,
      },
    });

    this.logger.log(`Form template created: ${template.id}`);
    return template;
  }

  // ============================================
  // 2. 获取表单模板列表
  // ============================================

  async findAll(query: QueryFormTemplatesDto, userId?: string) {
    const { category, isPublic, search, page = 1, limit = 20 } = query;

    const where: Prisma.FormTemplateWhereInput = {};

    if (category) {
      where.category = category;
    }

    if (isPublic !== undefined) {
      where.isPublic = isPublic;
    }

    // 如果不是查询公开模板，只能查看自己创建的
    if (isPublic === false && userId) {
      where.createdBy = userId;
    }

    if (search) {
      // 搜索需要在 JSON 字段中进行，这里简化处理
      where.OR = [
        { category: { contains: search, mode: 'insensitive' } },
      ];
    }

    const [items, total] = await Promise.all([
      this.prisma.formTemplate.findMany({
        where,
        skip: (page - 1) * limit,
        take: limit,
        orderBy: { createdAt: 'desc' },
        include: {
          creator: {
            select: {
              id: true,
              displayName: true,
            },
          },
        },
      }),
      this.prisma.formTemplate.count({ where }),
    ]);

    return {
      items: items.map((item) => this.formatTemplateResponse(item)),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  // ============================================
  // 3. 获取单个表单模板
  // ============================================

  async findOne(templateIdentifier: string) {
    const template = await this.identifierResolver.resolveFormTemplate(
      templateIdentifier
    );

    const fullTemplate = await this.prisma.formTemplate.findUnique({
      where: { id: template.id },
      include: {
        creator: {
          select: {
            id: true,
            displayName: true,
          },
        },
      },
    });

    return this.formatTemplateResponse(fullTemplate);
  }

  // ============================================
  // 4. 更新表单模板
  // ============================================

  async update(
    templateIdentifier: string,
    dto: UpdateFormTemplateDto,
    updatedBy: string
  ) {
    this.logger.log(`Updating form template: ${templateIdentifier}`);

    const template = await this.identifierResolver.resolveFormTemplate(
      templateIdentifier
    );

    const updated = await this.prisma.formTemplate.update({
      where: { id: template.id },
      data: {
        ...dto,
        updatedBy,
      },
      include: {
        creator: {
          select: {
            id: true,
            displayName: true,
          },
        },
      },
    });

    this.logger.log(`Form template updated: ${updated.id}`);
    return this.formatTemplateResponse(updated);
  }

  // ============================================
  // 5. 删除表单模板
  // ============================================

  async remove(templateIdentifier: string) {
    this.logger.log(`Deleting form template: ${templateIdentifier}`);

    const template = await this.identifierResolver.resolveFormTemplate(
      templateIdentifier
    );

    await this.prisma.formTemplate.delete({
      where: { id: template.id },
    });

    this.logger.log(`Form template deleted: ${template.id}`);
    return {
      id: template.id,
      deleted: true,
    };
  }

  // ============================================
  // 6. 从模板创建表单
  // ============================================

  async createFormFromTemplate(
    templateIdentifier: string,
    dto: CreateFormFromTemplateDto,
    createdBy: string
  ) {
    this.logger.log(
      `Creating form from template: ${templateIdentifier}`
    );

    const template = await this.identifierResolver.resolveFormTemplate(
      templateIdentifier
    );

    // 提取模板内容
    const templateData = template.template as any;

    // 创建新表单定义
    const newForm = await this.formDefinitionService.create(
      {
        slug: dto.slug,
        nameI18n: dto.name,
        descriptionI18n: templateData.descriptionI18n,
        category: dto.category || template.category,
        icon: templateData.icon || template.icon,
        color: templateData.color || template.color,
        defaultLocale: templateData.defaultLocale || 'zh-CN',
        supportedLocales: templateData.supportedLocales || ['zh-CN'],
        schema: templateData.schema,
        uiSchema: templateData.uiSchema,
        validation: templateData.validation,
        translations: templateData.translations,
        requiresApproval: templateData.requiresApproval || false,
        approvalProcessKey: templateData.approvalProcessKey,
      },
      createdBy
    );

    this.logger.log(`Form created from template: ${newForm.id}`);
    return newForm;
  }

  // ============================================
  // 私有辅助方法
  // ============================================

  /**
   * 格式化模板响应
   */
  private formatTemplateResponse(template: any) {
    const { creator, ...templateData } = template;

    return {
      ...templateData,
      creator: creator
        ? {
            id: creator.id,
            username: creator.username,
            name: creator.name,
          }
        : undefined,
    };
  }
}

