import { NextResponse } from 'next/server';

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

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

// DELETE /api/v1/berths/[id]/maintenance/[logId]
export const DELETE = withAuth(
  withPermission('berths', 'edit', async (_req, ctx, params) => {
    try {
      await assertMaintenanceModuleEnabled(ctx.portId);
      await deleteMaintenanceLog(params.id!, params.logId!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
