import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { addMaintenanceLogSchema } from '@/lib/validators/berths';
import { getMaintenanceLogs, addMaintenanceLog } from '@/lib/services/berths.service';
import { assertMaintenanceModuleEnabled } from '@/lib/services/maintenance-module.service';
import { errorResponse } from '@/lib/errors';

// GET /api/v1/berths/[id]/maintenance
export const GET = withAuth(
  withPermission('berths', 'view', async (req, ctx, params) => {
    try {
      await assertMaintenanceModuleEnabled(ctx.portId);
      const logs = await getMaintenanceLogs(params.id!, ctx.portId);
      return NextResponse.json({ data: logs });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// POST /api/v1/berths/[id]/maintenance
export const POST = withAuth(
  withPermission('berths', 'edit', async (req, ctx, params) => {
    try {
      await assertMaintenanceModuleEnabled(ctx.portId);
      const body = await parseBody(req, addMaintenanceLogSchema);
      const log = await addMaintenanceLog(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: log }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
