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;
    const id = event.context.params?.id || '0';

    if (!id) {
        return {
            success: false,
            message: 'Invalid ID'
        };
    }

    // GET - Get single hak akses by ID
    if (method === 'GET') {
        const data = readData();
        const hakAkses = data.find(item => item.id === id);
        
        if (hakAkses) {
            return {
                success: true,
                data: hakAkses
            };
        } else {
            return {
                success: false,
                message: 'Hak akses tidak ditemukan'
            };
        }
    }

    // PUT - Update hak akses
    if (method === 'PUT') {
        try {
            const body = await readBody(event);
            const data = readData();
            const index = data.findIndex(item => item.id === id);
            
            if (index === -1) {
                return {
                    success: false,
                    message: 'Hak akses tidak ditemukan'
                };
            }
            
            // Update the item
            data[index] = {
                id,
                namaHakAkses: body.namaHakAkses,
                status: body.status,
                pages: body.pages || []
            };
            
            const success = writeData(data);
            
            if (success) {
                return {
                    success: true,
                    message: 'Hak akses berhasil diupdate',
                    data: data[index]
                };
            } else {
                throw new Error('Failed to save data');
            }
        } catch (error) {
            return {
                success: false,
                message: 'Gagal mengupdate hak akses',
                error: error instanceof Error ? error.message : 'Unknown error'
            };
        }
    }

    // DELETE - Delete hak akses
    if (method === 'DELETE') {
        try {
            const data = readData();
            const index = data.findIndex(item => item.id === id);
            
            if (index === -1) {
                return {
                    success: false,
                    message: 'Hak akses tidak ditemukan'
                };
            }
            
            const deletedItem = data[index];
            data.splice(index, 1);
            
            const success = writeData(data);
            
            if (success) {
                return {
                    success: true,
                    message: 'Hak akses berhasil dihapus',
                    data: deletedItem
                };
            } else {
                throw new Error('Failed to save data');
            }
        } catch (error) {
            return {
                success: false,
                message: 'Gagal menghapus hak akses',
                error: error instanceof Error ? error.message : 'Unknown error'
            };
        }
    }

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