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

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

    async getPaymentSettings() {
        const settings = await this.prisma.systemSettings.findMany({
            where: { category: 'PAYMENT' },
        });

        // Transform list into object
        return settings.reduce((acc: Record<string, string>, curr) => {
            acc[curr.key] = curr.value;
            return acc;
        }, {} as Record<string, string>);
    }

    async setPaymentSetting(key: string, value: string, isSecure = true) {
        return this.prisma.systemSettings.upsert({
            where: { key },
            update: { value, isSecure },
            create: {
                key,
                value,
                category: 'PAYMENT',
                isSecure,
            },
        });
    }

    // Helper to bulk update
    async updatePaymentSettings(settings: Record<string, string>) {
        const promises = Object.entries(settings).map(([key, value]) =>
            this.setPaymentSetting(key, value, key.includes('SECRET') || key.includes('KEY')),
        );
        return Promise.all(promises);
    }
}
