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

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

  // ==================== 公众端 ====================

  /** 获取启用的标签列表（用户端选标签用） */
  async getPublicTags() {
    return this.prisma.workTag.findMany({
      where: { status: 'enabled' },
      orderBy: [{ sort: 'asc' }, { usageCount: 'desc' }],
      select: { id: true, name: true, category: true, usageCount: true },
    });
  }

  /** 热门标签（按使用次数排序，取前 20） */
  async getHotTags() {
    return this.prisma.workTag.findMany({
      where: { status: 'enabled', usageCount: { gt: 0 } },
      orderBy: { usageCount: 'desc' },
      take: 20,
      select: { id: true, name: true, category: true, usageCount: true },
    });
  }

  // ==================== 超管端 ====================

  /** 标签管理列表（含使用统计） */
  async getAdminList() {
    return this.prisma.workTag.findMany({
      orderBy: [{ category: 'asc' }, { sort: 'asc' }],
    });
  }

  /** 创建标签 */
  async create(dto: { name: string; category?: string; sort?: number }) {
    const existing = await this.prisma.workTag.findFirst({ where: { name: dto.name } });
    if (existing) throw new BadRequestException('标签名已存在');

    return this.prisma.workTag.create({
      data: {
        name: dto.name,
        category: dto.category || null,
        sort: dto.sort || 0,
      },
    });
  }

  /** 编辑标签 */
  async update(id: number, dto: { name?: string; category?: string; sort?: number; status?: string }) {
    const tag = await this.prisma.workTag.findUnique({ where: { id } });
    if (!tag) throw new NotFoundException('标签不存在');

    if (dto.name && dto.name !== tag.name) {
      const dup = await this.prisma.workTag.findFirst({ where: { name: dto.name } });
      if (dup) throw new BadRequestException('标签名已存在');
    }

    return this.prisma.workTag.update({
      where: { id },
      data: {
        name: dto.name ?? tag.name,
        category: dto.category !== undefined ? dto.category : tag.category,
        sort: dto.sort !== undefined ? dto.sort : tag.sort,
        status: dto.status ?? tag.status,
      },
    });
  }

  /** 删除标签 */
  async remove(id: number) {
    const tag = await this.prisma.workTag.findUnique({ where: { id } });
    if (!tag) throw new NotFoundException('标签不存在');
    if (tag.usageCount > 0) throw new BadRequestException('该标签已被使用，无法删除，请先禁用');

    return this.prisma.workTag.delete({ where: { id } });
  }

  /** 启用/禁用标签 */
  async toggleStatus(id: number) {
    const tag = await this.prisma.workTag.findUnique({ where: { id } });
    if (!tag) throw new NotFoundException('标签不存在');

    return this.prisma.workTag.update({
      where: { id },
      data: { status: tag.status === 'enabled' ? 'disabled' : 'enabled' },
    });
  }

  /** 获取标签分类列表 */
  async getCategories() {
    const tags = await this.prisma.workTag.findMany({
      where: { category: { not: null } },
      select: { category: true },
      distinct: ['category'],
    });
    return tags.map((t) => t.category).filter(Boolean);
  }
}
