import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { connectorCreateSchema, type ConnectorCreateInput } from '@/lib/api/schemas'
import { prisma } from '@/lib/db'
import { getHubOverview } from '@/lib/services/integration-service'

export const dynamic = 'force-dynamic'

/**
 * The hub overview.
 *
 * Every connector carries both `mode` and `status`, plus the `label` derived from the
 * pair — so a client cannot render "CONNECTED" against a synthetic source by reading one
 * field and forgetting the other.
 */
export const GET = apiRoute({ permission: 'integrations.read' }, async () => getHubOverview())

/** Register a data source. Accepts a secret's *name*, never its value. */
export const POST = apiRoute<Record<string, string>, ConnectorCreateInput>(
  { permission: 'integrations.manage', bodySchema: connectorCreateSchema, limit: 20 },
  async ({ body, user, request }) => {
    const existing = await prisma.integrationConnector.findUnique({
      where: { code: body.code },
      select: { id: true },
    })
    if (existing) throw new ApiError(ERROR_CODES.conflict)

    const connector = await prisma.integrationConnector.create({
      data: {
        code: body.code,
        name: body.name,
        nameAr: body.nameAr,
        kind: body.kind,
        protocol: body.protocol ?? 'rest',
        mode: body.mode ?? 'demo',
        // A new connector starts disconnected. Creating one already "connected" would be
        // asserting a link nobody has tested.
        status: 'disconnected',
        direction: body.direction ?? 'inbound',
        description: body.description ?? '',
        descriptionAr: body.descriptionAr ?? '',
        endpoint: body.endpoint ?? '',
        authKind: body.authKind ?? 'none',
        secretRef: body.secretRef ?? '',
        pollSeconds: body.pollSeconds ?? 15,
        timeoutMs: body.timeoutMs ?? 5_000,
      },
    })

    await writeAudit({
      action: AUDIT_ACTIONS.connectorCreated,
      entity: 'integration_connector',
      entityId: connector.code,
      user,
      request,
      detail: `${body.kind} (${body.mode ?? 'demo'})`,
    })

    return { code: connector.code, status: connector.status, mode: connector.mode }
  },
)
