import { updateBerth } from "../utils/nocodb";
import { requireAuth } from "../utils/auth";

export default defineEventHandler(async (event) => {
  console.log('[update-berth] Request received');

  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);

  try {
    const body = await readBody(event);
    const { berthId, updates } = body;
    
    if (!berthId) {
      throw createError({ 
        statusCode: 400, 
        statusMessage: "Berth ID is required" 
      });
    }

    if (!updates || typeof updates !== 'object') {
      throw createError({ 
        statusCode: 400, 
        statusMessage: "Updates object is required" 
      });
    }

    console.log('[update-berth] Updating berth ID:', berthId);
    console.log('[update-berth] Updates:', Object.keys(updates));
    
    const updatedBerth = await updateBerth(berthId.toString(), updates);
    
    console.log('[update-berth] Successfully updated berth:', berthId);
    return updatedBerth;
  } catch (error) {
    console.error('[update-berth] Error occurred:', error);
    console.error('[update-berth] Error details:', error instanceof Error ? error.message : 'Unknown error');
    throw error;
  }
});
