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

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

// Helper to read JSON file
const readData = (): HakAkses[] => {
    try {
        if (!fs.existsSync(filePath)) {
            // Ensure directory exists
            const dir = path.dirname(filePath);
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
            fs.writeFileSync(filePath, '[]', 'utf-8');
            return [];
        }
        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;
    }
};

export default defineEventHandler(async (event) => {
    const method = event.method;

    // GET - List all hak akses
    if (method === 'GET') {
        const data = readData();
        return {
            success: true,
            data
        };
    }

    // POST - Create or Update hak akses
    if (method === 'POST') {
        try {
            const body = await readBody(event);
            const data = readData();
            
            if (body.id) {
                // Update existing
                const index = data.findIndex(h => h.id === body.id);
                if (index !== -1) {
                    data[index] = {
                        ...data[index],
                        ...body
                    };
                } else {
                    data.push(body);
                }
            } else {
                // Create new
                const newId = randomUUID();
                const newHakAkses: HakAkses = {
                    id: newId,
                    namaHakAkses: body.namaHakAkses,
                    status: body.status || 'aktif',
                    pages: body.pages || []
                };
                data.push(newHakAkses);
            }
            
            const success = writeData(data);
            
            if (success) {
                return {
                    success: true,
                    message: 'Hak akses berhasil disimpan',
                    data: body.id ? body : data[data.length - 1]
                };
            } else {
                throw new Error('Failed to save data');
            }
        } catch (error) {
            return {
                success: false,
                message: 'Gagal menyimpan hak akses',
                error: error instanceof Error ? error.message : 'Unknown error'
            };
        }
    }

    return {
        success: false,
        message: 'Method not allowed'
    };
});
