import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateConfigDto } from './dto/create-config.dto';
import { UpdateConfigDto } from './dto/update-config.dto';

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

  async create(createConfigDto: CreateConfigDto, tenantId: number) {
    return this.prisma.config.create({
      data: {
        ...createConfigDto,
        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.config.findMany({
        where,
        skip,
        take: pageSize,
      }),
      this.prisma.config.count({ where }),
    ]);

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

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

    const config = await this.prisma.config.findFirst({
      where,
    });

    if (!config) {
      throw new NotFoundException('配置不存在');
    }

    return config;
  }

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

    return this.prisma.config.findFirst({
      where: {
        key,
        tenantId,
      },
    });
  }

  async update(id: number, updateConfigDto: UpdateConfigDto, tenantId?: number) {
    // 验证配置是否存在且属于该租户
    await this.findOne(id, tenantId);

    return this.prisma.config.update({
      where: { id },
      data: updateConfigDto,
    });
  }

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

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