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

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

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