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 { renewTenancy } from '@/lib/services/berth-tenancies.service';
import { assertTenanciesModuleEnabled } from '@/lib/services/tenancies-module.service';
import { renewTenancySchema } from '@/lib/validators/tenancies';

const renewHandler: RouteHandler = async (req, ctx, params) => {
  try {
    await assertTenanciesModuleEnabled(ctx.portId);
    const body = await parseBody(req, renewTenancySchema);
    const result = await renewTenancy(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', renewHandler));
