import fs from 'fs';
import path from 'path';
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;
    }
};

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 new hak akses
    if (method === 'POST') {
        try {
            const body = await readBody(event);
            const data = readData();
            
            // Generate new ID
            //random uuid
            const newId = crypto.randomUUID();
            
            const newHakAkses: HakAkses = {
                id: newId,
                namaHakAkses: body.namaHakAkses,
                status: body.status,
                pages: body.pages || []
            };
            
            data.push(newHakAkses);
            
            const success = writeData(data);
            
            if (success) {
                return {
                    success: true,
                    message: 'Hak akses berhasil ditambahkan',
                    data: newHakAkses
                };
            } else {
                throw new Error('Failed to save data');
            }
        } catch (error) {
            return {
                success: false,
                message: 'Gagal menambahkan hak akses',
                error: error instanceof Error ? error.message : 'Unknown error'
            };
        }
    }

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