import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { resetBerthOverrideSchema } from '@/lib/validators/berths';
import { resetBerthStatusOverride } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';

// POST /api/v1/berths/[id]/status/reset
// Clears a manual status pin so the berth resumes derived/automatic status.
export const POST = withAuth(
  withPermission('berths', 'edit', async (req, ctx, params) => {
    try {
      const { reason } = await parseBody(req, resetBerthOverrideSchema);
      const updated = await resetBerthStatusOverride(params.id!, ctx.portId, reason, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: updated });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
