import { defineEventHandler, readBody } from 'h3';
import fs from 'fs';
import path from 'path';

// Path to the mock JSON file
const filePath = path.resolve(process.cwd(), 'public/data/patient_subspesialis.json');

// Ensure directory and file exist
const ensureFileExists = () => {
  const dirPath = path.dirname(filePath);
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, JSON.stringify({}, null, 2), 'utf-8');
  }
};

export default defineEventHandler(async (event) => {
  ensureFileExists();
  
  if (event.node.req.method === 'GET') {
    // Return all mappings
    try {
      const data = fs.readFileSync(filePath, 'utf-8');
      return JSON.parse(data);
    } catch (e) {
      return {};
    }
  } 
  
  if (event.node.req.method === 'POST') {
    // Save a new mapping
    try {
      const body = await readBody(event);
      const { barcode, subspesialis } = body;
      
      if (!barcode || !subspesialis) {
        return { success: false, message: 'Barcode and subspesialis are required' };
      }
      
      const fileData = fs.readFileSync(filePath, 'utf-8');
      const data = JSON.parse(fileData);
      
      // Save mapping: barcode -> subspesialis object
      data[barcode] = subspesialis;
      
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
      return { success: true, message: 'Saved successfully' };
    } catch (e) {
      return { success: false, message: e.message };
    }
  }
});
