import fs from 'fs';
import path from 'path';

interface User {
    id: string;
    namaUser: string;
    email: string;
    hakAkses: string[];
    status: string;
}

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

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

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

/**
 * Sync user data from Keycloak to users.json
 * Add user if not exists, update hakAkses if exists
 */
export const syncUserData = (userData: {
    id: string;
    name: string;
    email: string;
    roles: string[];
}): { action: 'created' | 'updated' | 'skipped', message: string } => {
    const data = readData();
    
    // Check if user exists
    const existingUserIndex = data.findIndex(user => user.id === userData.id);
    
    if (existingUserIndex === -1) {
        // User doesn't exist, create new
        const newUser: User = {
            id: userData.id,
            namaUser: userData.name,
            email: userData.email,
            hakAkses: userData.roles,
            status: 'aktif'
        };
        
        data.push(newUser);
        
        const success = writeData(data);
        if (success) {
            console.log(`✅ Created new user: ${userData.name} (${userData.email})`);
            return {
                action: 'created',
                message: `User ${userData.name} created successfully`
            };
        } else {
            console.error('❌ Failed to create user');
            return {
                action: 'skipped',
                message: 'Failed to write user data'
            };
        }
    } else {
        // User exists, update hakAkses if different
        const existingUser = data[existingUserIndex];
        const rolesChanged = JSON.stringify(existingUser.hakAkses.sort()) !== JSON.stringify(userData.roles.sort());
        
        if (rolesChanged) {
            existingUser.hakAkses = userData.roles;
            
            const success = writeData(data);
            if (success) {
                console.log(`✅ Updated user roles: ${userData.name}`);
                return {
                    action: 'updated',
                    message: `User ${userData.name} roles updated`
                };
            } else {
                console.error('❌ Failed to update user');
                return {
                    action: 'skipped',
                    message: 'Failed to write user data'
                };
            }
        } else {
            console.log(`ℹ️ User ${userData.name} already exists with same roles`);
            return {
                action: 'skipped',
                message: `User ${userData.name} already up to date`
            };
        }
    }
};
