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

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

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