import { NextResponse } from 'next/server';

import type { AuthContext } from '@/lib/api/helpers';
import { parseBody, parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createPending, listTenancies } from '@/lib/services/berth-tenancies.service';
import { assertTenanciesModuleEnabled } from '@/lib/services/tenancies-module.service';
import { createPendingSchema, listTenanciesSchema } from '@/lib/validators/tenancies';

/**
 * Port-scoped global list of tenancies across all berths. Inner handler
 * lives here so it can be invoked directly from integration tests without
 * the `withAuth(withPermission(...))` wrappers (matches the convention
 * used throughout `src/app/api/v1/*`).
 */
export async function listHandler(req: Request, ctx: AuthContext): Promise<NextResponse> {
  try {
    await assertTenanciesModuleEnabled(ctx.portId);
    const query = parseQuery(req as never, listTenanciesSchema);
    const result = await listTenancies(ctx.portId, query);
    const { page, limit } = query;
    const totalPages = Math.ceil(result.total / limit);
    return NextResponse.json({
      data: result.data,
      pagination: {
        page,
        pageSize: limit,
        total: result.total,
        totalPages,
        hasNextPage: page < totalPages,
        hasPreviousPage: page > 1,
      },
    });
  } catch (error) {
    return errorResponse(error);
  }
}

/**
 * Generic create endpoint — accepts berthId in the body, so client / yacht
 * tab entry points can mint a tenancy without bouncing through a
 * berth-specific URL. Same service helper as POST /api/v1/berths/[id]/tenancies;
 * the URL just differs in where berthId arrives from.
 */
export async function createHandler(req: Request, ctx: AuthContext): Promise<NextResponse> {
  try {
    await assertTenanciesModuleEnabled(ctx.portId);
    const body = await parseBody(req as never, createPendingSchema);
    const tenancy = await createPending(ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: tenancy }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
}
