import { Injectable } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { AdminSettingsDto } from './dto/approval.dto';
import { AdminSettingsResponse } from './dto/approval-response.dto';

const ADMIN_CONFIG_KEY = 'approval.adminAnalytics';
const DEFAULT_SETTINGS: AdminSettingsResponse = {
  exportRetentionDays: 30,
};

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

  async getSettings(): Promise<AdminSettingsResponse> {
    const config = await this.prisma.approvalAdminConfig.findUnique({
      where: { key: ADMIN_CONFIG_KEY },
      select: { value: true },
    });

    if (!config) {
      return { ...DEFAULT_SETTINGS };
    }

    return {
      exportRetentionDays:
        (config.value as { exportRetentionDays?: number }).exportRetentionDays
          ?? DEFAULT_SETTINGS.exportRetentionDays,
    };
  }

  async updateSettings(
    dto: AdminSettingsDto,
    userId: string,
  ): Promise<AdminSettingsResponse> {
    const value = {
      exportRetentionDays: dto.exportRetentionDays,
    };

    const record = await this.prisma.approvalAdminConfig.upsert({
      where: { key: ADMIN_CONFIG_KEY },
      update: {
        value,
        updatedBy: userId,
      },
      create: {
        key: ADMIN_CONFIG_KEY,
        value,
        description: '审批中心管理员数据中心配置',
        updatedBy: userId,
      },
      select: { value: true },
    });

    return {
      exportRetentionDays:
        (record.value as { exportRetentionDays?: number }).exportRetentionDays
          ?? DEFAULT_SETTINGS.exportRetentionDays,
    };
  }
}
