import fs from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
import type { HakAkses } from '~/types/setting';

const filePath = path.resolve('data/mock/hakAkses.json');

// Helper to read JSON file
const readData = (): HakAkses[] => {
    try {
        const data = fs.readFileSync(filePath, 'utf-8');
        return JSON.parse(data);
    } catch (error) {
        console.error('Error reading hakAkses.json:', error);
        return [];
    }
};

// Helper to write JSON file
const writeData = (data: HakAkses[]): boolean => {
    try {
        fs.writeFileSync(filePath, JSON.stringify(data, null, 4), 'utf-8');
        return true;
    } catch (error) {
        console.error('Error writing hakAkses.json:', error);
        return false;
    }
};

/**
 * Sync roles from Keycloak to hakAkses.json
 * Add any missing roles with inactive status and empty pages
 */
export const syncHakAksesFromRoles = (roles: string[]): { added: string[], skipped: string[] } => {
    const data = readData();
    const added: string[] = [];
    const skipped: string[] = [];
    
    let hasChanges = false;
    
    for (const role of roles) {
        // Check if role already exists
        const exists = data.some(item => item.namaHakAkses === role);
        
        if (!exists) {
            // Generate new UUID
            const newId = randomUUID();
            
            // Add new hak akses
            const newHakAkses: HakAkses = {
                id: newId,
                namaHakAkses: role,
                status: 'tidak aktif',
                pages: []
            };
            
            data.push(newHakAkses);
            added.push(role);
            hasChanges = true;
            
            console.log(`✅ Added new hak akses: ${role} (id: ${newId})`);
        } else {
            skipped.push(role);
        }
    }
    
    // Write back to file if there are changes
    if (hasChanges) {
        const success = writeData(data);
        if (success) {
            console.log(`📝 Updated hakAkses.json with ${added.length} new roles`);
        } else {
            console.error('❌ Failed to update hakAkses.json');
        }
    }
    
    return { added, skipped };
};
