import { AUDIT_ACTIONS, writeAudit } from '@/lib/audit'
import { apiRoute } from '@/lib/api/handler'
import { ApiError, ERROR_CODES } from '@/lib/api/errors'
import { connectorSyncSchema, type ConnectorSyncInput } from '@/lib/api/schemas'
import { syncConnector } from '@/lib/services/integration-service'

export const dynamic = 'force-dynamic'

/**
 * Run one real pass of the pipeline.
 *
 * The counts returned are the counts the quality score was computed from — records that
 * genuinely failed mapping, range or duplicate checks. Nothing here is asserted.
 */
export const POST = apiRoute<{ code: string }, ConnectorSyncInput>(
  { permission: 'integrations.sync', bodySchema: connectorSyncSchema, limit: 30 },
  async ({ params, body, user, request }) => {
    const result = await syncConnector({ code: params.code, batchSize: body.batchSize })
    if (!result) throw new ApiError(ERROR_CODES.notFound)

    await writeAudit({
      action: AUDIT_ACTIONS.connectorSynced,
      entity: 'integration_connector',
      entityId: params.code,
      user,
      request,
      detail: `${result.accepted}/${result.recordsIn} accepted, quality ${result.quality.score}`,
    })

    return result
  },
)
