import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateDictDto } from './dto/create-dict.dto';
import { UpdateDictDto } from './dto/update-dict.dto';

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

  async create(createDictDto: CreateDictDto, tenantId: number) {
    return this.prisma.dict.create({
      data: {
        ...createDictDto,
        tenantId,
      },
    });
  }

  async findAll(page: number = 1, pageSize: number = 10, tenantId?: number) {
    const skip = (page - 1) * pageSize;
    const where = tenantId ? { tenantId } : {};

    const [list, total] = await Promise.all([
      this.prisma.dict.findMany({
        where,
        skip,
        take: pageSize,
        include: {
          items: {
            orderBy: {
              sort: 'asc',
            },
          },
        },
      }),
      this.prisma.dict.count({ where }),
    ]);

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

  async findOne(id: number, tenantId?: number) {
    const where: any = { id };
    if (tenantId) {
      where.tenantId = tenantId;
    }

    const dict = await this.prisma.dict.findFirst({
      where,
      include: {
        items: {
          orderBy: {
            sort: 'asc',
          },
        },
      },
    });

    if (!dict) {
      throw new NotFoundException('字典不存在');
    }

    return dict;
  }

  async findByCode(code: string, tenantId?: number) {
    if (!tenantId) {
      throw new NotFoundException('无法确定租户信息');
    }

    return this.prisma.dict.findFirst({
      where: {
        code,
        tenantId,
      },
      include: {
        items: {
          where: {
            validState: 1,
          },
          orderBy: {
            sort: 'asc',
          },
        },
      },
    });
  }

  async update(id: number, updateDictDto: UpdateDictDto, tenantId?: number) {
    // 验证字典是否存在且属于该租户
    await this.findOne(id, tenantId);

    return this.prisma.dict.update({
      where: { id },
      data: updateDictDto,
    });
  }

  async remove(id: number, tenantId?: number) {
    // 验证字典是否存在且属于该租户
    await this.findOne(id, tenantId);

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