import { sql } from 'drizzle-orm'
import type { Actor } from '@platform-modules/commerce-orders'
import type { Querier } from '@platform-modules/db'
import { DownloadNotFoundError } from '../errors.js'
import type { StorageAdapter } from '../seams.js'
import type { FulfillmentSchema } from '../schema.js'
import { assertUuid, ownerKeyOf } from '../types.js'

export const DOWNLOAD_TTL_SECONDS = 3600

type SqlRow = Record<string, unknown>

function firstRow(res: unknown): SqlRow | undefined {
  const rows = (Array.isArray(res) ? res : (res as { rows?: SqlRow[] }).rows) ?? []
  return rows[0]
}

export async function issueDownloadToken(
  q: Querier<FulfillmentSchema>,
  grantId: string,
  requester: Actor | { guestEmail: string },
  storage: StorageAdapter,
): Promise<{ url: string; expiresAt?: Date }> {
  assertUuid(grantId, 'grantId')

  const reqKey = ownerKeyOf(requester)

  const grantRes = await q.execute(sql`
    SELECT owner_key, blob_key
    FROM access_grant
    WHERE id = ${grantId}::uuid
  `)
  const grant = firstRow(grantRes)

  if (!grant || String(grant.owner_key) !== reqKey) {
    throw new DownloadNotFoundError(grantId)
  }

  return storage.signedUrl(String(grant.blob_key), DOWNLOAD_TTL_SECONDS)
}
