import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class UserWorksService {
  constructor(private prisma: PrismaService) {}

  /**
   * 创建作品（AI 生成完毕后调用）
   */
  async create(userId: number, dto: {
    title: string;
    coverUrl?: string;
    description?: string;
    visibility?: string;
    originalImageUrl?: string;
    voiceInputUrl?: string;
    textInput?: string;
    aiMeta?: any;
    pages?: Array<{ pageNo: number; imageUrl?: string; text?: string; audioUrl?: string }>;
    tagIds?: number[];
  }) {
    return this.prisma.$transaction(async (tx) => {
      const work = await tx.userWork.create({
        data: {
          userId,
          title: dto.title,
          coverUrl: dto.coverUrl || null,
          description: dto.description || null,
          visibility: dto.visibility || 'private',
          status: 'draft',
          originalImageUrl: dto.originalImageUrl || null,
          voiceInputUrl: dto.voiceInputUrl || null,
          textInput: dto.textInput || null,
          aiMeta: dto.aiMeta || null,
        },
      });

      // 创建绘本分页
      if (dto.pages && dto.pages.length > 0) {
        await tx.userWorkPage.createMany({
          data: dto.pages.map((p) => ({
            workId: work.id,
            pageNo: p.pageNo,
            imageUrl: p.imageUrl || null,
            text: p.text || null,
            audioUrl: p.audioUrl || null,
          })),
        });
      }

      // 关联标签
      if (dto.tagIds && dto.tagIds.length > 0) {
        await tx.workTagRelation.createMany({
          data: dto.tagIds.map((tagId) => ({
            workId: work.id,
            tagId,
          })),
        });
        // 更新标签使用次数
        await tx.workTag.updateMany({
          where: { id: { in: dto.tagIds } },
          data: { usageCount: { increment: 1 } },
        });
      }

      return this.findOne(work.id, userId);
    });
  }

  /**
   * 获取我的作品列表
   */
  async findMyWorks(userId: number, params: {
    page?: number;
    pageSize?: number;
    status?: string;
    keyword?: string;
  }) {
    const { page = 1, pageSize = 10, status, keyword } = params;
    const skip = (page - 1) * pageSize;

    const where: any = { userId, isDeleted: 0 };
    if (status) where.status = status;
    if (keyword) {
      where.OR = [
        { title: { contains: keyword } },
        { description: { contains: keyword } },
      ];
    }

    const [list, total] = await Promise.all([
      this.prisma.userWork.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: { createTime: 'desc' },
        include: {
          tags: { include: { tag: true } },
          _count: { select: { pages: true } },
        },
      }),
      this.prisma.userWork.count({ where }),
    ]);

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

  /**
   * 获取作品详情（含分页内容）
   */
  async findOne(workId: number, userId?: number) {
    const where: any = { id: workId, isDeleted: 0 };
    // 非作者只能看已发布的
    if (userId) {
      // 作者可以看自己所有状态的作品
    } else {
      where.status = 'published';
      where.visibility = 'public';
    }

    const work = await this.prisma.userWork.findFirst({
      where: userId ? { id: workId, isDeleted: 0, userId } : where,
      include: {
        pages: { orderBy: { pageNo: 'asc' } },
        tags: { include: { tag: true } },
        creator: {
          select: { id: true, nickname: true, avatar: true, username: true },
        },
        _count: { select: { pages: true, likes: true, favorites: true, comments: true } },
      },
    });

    if (!work) {
      throw new NotFoundException('作品不存在');
    }

    return work;
  }

  /**
   * 更新作品信息
   */
  async update(workId: number, userId: number, dto: {
    title?: string;
    description?: string;
    coverUrl?: string;
    visibility?: string;
    tagIds?: number[];
  }) {
    const work = await this.prisma.userWork.findFirst({
      where: { id: workId, userId, isDeleted: 0 },
    });
    if (!work) throw new NotFoundException('作品不存在');

    const updateData: any = {};
    if (dto.title !== undefined) updateData.title = dto.title;
    if (dto.description !== undefined) updateData.description = dto.description;
    if (dto.coverUrl !== undefined) updateData.coverUrl = dto.coverUrl;
    if (dto.visibility !== undefined) updateData.visibility = dto.visibility;

    return this.prisma.$transaction(async (tx) => {
      if (Object.keys(updateData).length > 0) {
        await tx.userWork.update({ where: { id: workId }, data: updateData });
      }

      // 更新标签
      if (dto.tagIds !== undefined) {
        // 获取旧标签
        const oldTags = await tx.workTagRelation.findMany({ where: { workId } });
        const oldTagIds = oldTags.map((t) => t.tagId);

        // 删除旧标签关联
        await tx.workTagRelation.deleteMany({ where: { workId } });
        // 旧标签使用次数减 1
        if (oldTagIds.length > 0) {
          await tx.workTag.updateMany({
            where: { id: { in: oldTagIds } },
            data: { usageCount: { decrement: 1 } },
          });
        }

        // 创建新标签关联
        if (dto.tagIds.length > 0) {
          await tx.workTagRelation.createMany({
            data: dto.tagIds.map((tagId) => ({ workId, tagId })),
          });
          await tx.workTag.updateMany({
            where: { id: { in: dto.tagIds } },
            data: { usageCount: { increment: 1 } },
          });
        }
      }

      return this.findOne(workId, userId);
    });
  }

  /**
   * 发布作品（进入审核队列）
   */
  async publish(workId: number, userId: number) {
    const work = await this.prisma.userWork.findFirst({
      where: { id: workId, userId, isDeleted: 0 },
    });
    if (!work) throw new NotFoundException('作品不存在');
    if (work.status !== 'draft' && work.status !== 'rejected') {
      throw new BadRequestException('只有草稿或被拒绝的作品才能提交发布');
    }

    return this.prisma.userWork.update({
      where: { id: workId },
      data: {
        status: 'pending_review',
        visibility: work.visibility === 'private' ? 'public' : work.visibility,
      },
    });
  }

  /**
   * 删除作品（软删除）
   */
  async remove(workId: number, userId: number) {
    const work = await this.prisma.userWork.findFirst({
      where: { id: workId, userId, isDeleted: 0 },
    });
    if (!work) throw new NotFoundException('作品不存在');

    return this.prisma.userWork.update({
      where: { id: workId },
      data: { isDeleted: 1 },
    });
  }

  /**
   * 保存/更新绘本分页数据
   */
  async savePages(workId: number, userId: number, pages: Array<{
    pageNo: number;
    imageUrl?: string;
    text?: string;
    audioUrl?: string;
  }>) {
    const work = await this.prisma.userWork.findFirst({
      where: { id: workId, userId, isDeleted: 0 },
    });
    if (!work) throw new NotFoundException('作品不存在');

    return this.prisma.$transaction(async (tx) => {
      // 删除旧分页
      await tx.userWorkPage.deleteMany({ where: { workId } });
      // 创建新分页
      await tx.userWorkPage.createMany({
        data: pages.map((p) => ({
          workId,
          pageNo: p.pageNo,
          imageUrl: p.imageUrl || null,
          text: p.text || null,
          audioUrl: p.audioUrl || null,
        })),
      });

      return tx.userWorkPage.findMany({
        where: { workId },
        orderBy: { pageNo: 'asc' },
      });
    });
  }

  /**
   * 获取绘本分页数据
   */
  async getPages(workId: number) {
    return this.prisma.userWorkPage.findMany({
      where: { workId },
      orderBy: { pageNo: 'asc' },
    });
  }
}
