import { NextResponse } from 'next/server';
import { eq, and } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { berths } from '@/lib/db/schema/berths';
import { loadEntityActivity } from '@/lib/services/entity-activity.service';
import { errorResponse, NotFoundError } from '@/lib/errors';

export const GET = withAuth(
  withPermission('berths', 'view', async (_req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('berth');
      const exists = await db
        .select({ id: berths.id })
        .from(berths)
        .where(and(eq(berths.id, id), eq(berths.portId, ctx.portId)))
        .limit(1);
      if (exists.length === 0) throw new NotFoundError('berth');
      const data = await loadEntityActivity({
        portId: ctx.portId,
        entityType: 'berth',
        entityId: id,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
