import { NextResponse } from 'next/server';

import { withAuth, withPermission, type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { transferTenancy } from '@/lib/services/berth-tenancies.service';
import { assertTenanciesModuleEnabled } from '@/lib/services/tenancies-module.service';
import { transferTenancySchema } from '@/lib/validators/tenancies';

const transferHandler: RouteHandler = async (req, ctx, params) => {
  try {
    await assertTenanciesModuleEnabled(ctx.portId);
    const body = await parseBody(req, transferTenancySchema);
    const result = await transferTenancy(params.id!, ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
};

export const POST = withAuth(withPermission('tenancies', 'manage', transferHandler));
