/**
 * Tenant export job query helpers — audit-compliance (wave-11 leaf-D).
 * Tracks async GDPR data export requests against tenantExportJobs table
 * (distinct from legacy exportJobs table used by data-export.ts).
 */
import { and, eq } from 'drizzle-orm'
import type { Db } from '../client'
import { tenantExportJobs } from '../schema/tenant-export-jobs'

export interface TenantExportJobObject {
  id: string
  tenantId: string
  status: 'PENDING' | 'PROCESSING' | 'DONE' | 'FAILED'
  r2Key: string | null
  createdBy: string | null
  createdAt: string
  completedAt: string | null
}

function serializeJob(row: typeof tenantExportJobs.$inferSelect): TenantExportJobObject {
  return {
    id: row.id,
    tenantId: row.tenantId,
    status: row.status as TenantExportJobObject['status'],
    r2Key: row.r2Key ?? null,
    createdBy: row.createdBy ?? null,
    createdAt: row.createdAt.toISOString(),
    completedAt: row.completedAt ? row.completedAt.toISOString() : null,
  }
}

export async function createTenantExportJob(
  db: Db,
  input: { tenantId: string; createdBy?: string },
): Promise<TenantExportJobObject> {
  const rows = await db
    .insert(tenantExportJobs)
    .values({
      tenantId: input.tenantId,
      createdBy: input.createdBy ?? null,
      status: 'PENDING',
    })
    .returning()

  if (!rows[0]) throw new Error('Failed to create export job')
  return serializeJob(rows[0])
}

export async function getTenantExportJobById(
  db: Db,
  id: string,
  tenantId: string,
): Promise<TenantExportJobObject | null> {
  const rows = await db
    .select()
    .from(tenantExportJobs)
    .where(and(eq(tenantExportJobs.tenantId, tenantId), eq(tenantExportJobs.id, id)))
    .limit(1)

  const row = rows[0]
  if (!row) return null
  return serializeJob(row)
}

export async function markTenantExportJobStatus(
  db: Db,
  tenantId: string,
  id: string,
  status: 'PROCESSING' | 'DONE' | 'FAILED',
  r2Key?: string,
): Promise<void> {
  await db
    .update(tenantExportJobs)
    .set({
      status,
      r2Key: r2Key ?? null,
      completedAt: status === 'DONE' || status === 'FAILED' ? new Date() : null,
    })
    .where(and(eq(tenantExportJobs.tenantId, tenantId), eq(tenantExportJobs.id, id)))
}
