import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';

@Injectable()
export class ConfigManagementService {
  private readonly logger = new Logger(ConfigManagementService.name);

  constructor(private readonly prisma: PrismaService) {}

  async getConfigs(category?: string): Promise<any[]> {
    const where = category ? { category } : {};
    return this.prisma.systemConfig.findMany({ where, orderBy: [{ category: 'asc' }, { key: 'asc' }] });
  }

  async getConfig(category: string, key: string): Promise<any> {
    return this.prisma.systemConfig.findUnique({ where: { category_key: { category, key } } });
  }

  async setConfig(adminId: string, category: string, key: string, value: string, description?: string, ipAddress?: string, userAgent?: string): Promise<void> {
    const existing = await this.getConfig(category, key);

    await this.prisma.systemConfig.upsert({
      where: { category_key: { category, key } },
      create: { category, key, value, description },
      update: { value, description },
    });

    await this.prisma.auditLog.create({
      data: {
        adminId,
        action: existing ? 'UPDATE' : 'CREATE',
        resource: 'CONFIG',
        resourceId: `${category}:${key}`,
        oldValue: existing ? { value: existing.value } : undefined,
        newValue: { value },
        ipAddress,
        userAgent,
      },
    });
  }

  async recordAuditLog(adminId: string, action: string, resource: string, resourceId?: string, newValue?: any, ipAddress?: string, userAgent?: string): Promise<void> {
    await this.prisma.auditLog.create({
      data: { adminId, action, resource, resourceId, newValue, ipAddress, userAgent },
    });
  }

  async deleteConfig(adminId: string, category: string, key: string, ipAddress?: string, userAgent?: string): Promise<void> {
    const existing = await this.getConfig(category, key);
    if (!existing) return;

    await this.prisma.systemConfig.delete({ where: { category_key: { category, key } } });

    await this.prisma.auditLog.create({
      data: { adminId, action: 'DELETE', resource: 'CONFIG', resourceId: `${category}:${key}`, oldValue: existing, ipAddress, userAgent },
    });
  }
}
