import {
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UserWorksService } from './user-works.service';

/**
 * 创作流程服务
 *
 * 管理 AI 创作请求的生命周期：提交 → 生成中 → 完成/失败
 * AI 服务由同事提供，此模块做中间层对接
 *
 * P0 阶段：用简单的数据库记录模拟异步流程
 * 后续对接真实 AI 服务时替换 callAiService 方法即可
 */
@Injectable()
export class CreationService {
  constructor(
    private prisma: PrismaService,
    private userWorksService: UserWorksService,
  ) {}

  /**
   * 提交创作请求
   */
  async submit(userId: number, dto: {
    originalImageUrl: string;
    voiceInputUrl?: string;
    textInput?: string;
  }) {
    // 创建一个 draft 状态的作品记录，作为创作任务的载体
    const work = await this.prisma.userWork.create({
      data: {
        userId,
        title: '创作中...',
        status: 'draft',
        visibility: 'private',
        originalImageUrl: dto.originalImageUrl,
        voiceInputUrl: dto.voiceInputUrl || null,
        textInput: dto.textInput || null,
        aiMeta: { status: 'generating', submittedAt: new Date().toISOString() },
      },
    });

    // TODO: 调用同事的 AI 服务，传入 originalImageUrl + voiceInputUrl/textInput
    // AI 服务返回一个任务 ID，异步生成绘本
    // 这里模拟异步过程：实际对接时替换为真实 API 调用
    //
    // 示例：
    // const aiResult = await this.callAiService({
    //   imageUrl: dto.originalImageUrl,
    //   voiceUrl: dto.voiceInputUrl,
    //   text: dto.textInput,
    // });
    //
    // 将 aiResult.taskId 存入 aiMeta

    return {
      id: work.id,
      status: 'generating',
      message: '创作请求已提交，正在生成绘本...',
    };
  }

  /**
   * 查询创作进度
   */
  async getStatus(workId: number, userId: number) {
    const work = await this.prisma.userWork.findFirst({
      where: { id: workId, userId, isDeleted: 0 },
      select: {
        id: true,
        title: true,
        status: true,
        aiMeta: true,
        createTime: true,
      },
    });

    if (!work) throw new NotFoundException('创作任务不存在');

    const aiMeta = work.aiMeta as any;
    return {
      id: work.id,
      status: aiMeta?.status || work.status,
      title: work.title,
      createdAt: work.createTime,
    };
  }

  /**
   * AI 生成完成后的回调（由 AI 服务或定时任务调用）
   * 将生成结果写入作品库
   */
  async completeGeneration(workId: number, result: {
    title: string;
    coverUrl: string;
    pages: Array<{
      pageNo: number;
      imageUrl: string;
      text: string;
      audioUrl?: string;
    }>;
    aiMeta?: any;
  }) {
    return this.prisma.$transaction(async (tx) => {
      // 更新作品基本信息
      await tx.userWork.update({
        where: { id: workId },
        data: {
          title: result.title,
          coverUrl: result.coverUrl,
          status: 'draft',
          aiMeta: {
            ...(result.aiMeta || {}),
            status: 'completed',
            completedAt: new Date().toISOString(),
          },
        },
      });

      // 写入绘本分页
      if (result.pages.length > 0) {
        // 先清除旧分页
        await tx.userWorkPage.deleteMany({ where: { workId } });
        await tx.userWorkPage.createMany({
          data: result.pages.map((p) => ({
            workId,
            pageNo: p.pageNo,
            imageUrl: p.imageUrl,
            text: p.text,
            audioUrl: p.audioUrl || null,
          })),
        });
      }

      return { id: workId, status: 'completed' };
    });
  }

  /**
   * 获取创作结果
   */
  async getResult(workId: number, userId: number) {
    return this.userWorksService.findOne(workId, userId);
  }

  /**
   * 创作历史
   */
  async getHistory(userId: number, params: { page?: number; pageSize?: number }) {
    const { page = 1, pageSize = 10 } = params;
    const skip = (page - 1) * pageSize;

    const where = {
      userId,
      isDeleted: 0,
      originalImageUrl: { not: null }, // 只查有原画的（即通过创作流程创建的）
    };

    const [list, total] = await Promise.all([
      this.prisma.userWork.findMany({
        where: where as any,
        skip,
        take: pageSize,
        orderBy: { createTime: 'desc' },
        select: {
          id: true,
          title: true,
          coverUrl: true,
          status: true,
          originalImageUrl: true,
          aiMeta: true,
          createTime: true,
          _count: { select: { pages: true } },
        },
      }),
      this.prisma.userWork.count({ where: where as any }),
    ]);

    return { list, total, page, pageSize };
  }
}
