import { eq } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { order, orderLine } from '../schema.js';
import { createVoucher, createVoucherExtension } from './vouchers.js';

export async function findOrderIdByIdempotencyKey(
  db: DrizzleClient,
  idempotencyKey: string,
): Promise<string | null> {
  const [row] = await db
    .select({ id: order.id })
    .from(order)
    .where(eq(order.idempotencyKey, idempotencyKey))
    .limit(1);
  return row?.id ?? null;
}

export type SeedVoucherPurchaseInput = {
  buyerUserId: string;
  vendorId: string;
  variantId: string;
  amountAgorot: bigint;
  idempotencyKey: string;
  requestHash: string;
  orderStatus: 'paid' | 'pending';
  orderCreatedAt: Date;
  voucherId: string;
  redemptionStatus: 'UNREDEEMED' | 'REDEEMED' | 'EXPIRED' | 'CANCELLED';
  expiresAt: Date;
  redeemedAt: Date | null;
  qrTokenHash: string;
  reviewEligible: boolean;
};

/**
 * Idempotent at the order level: caller must check findOrderIdByIdempotencyKey first.
 */
export async function insertSeedVoucherPurchase(
  db: DrizzleClient,
  input: SeedVoucherPurchaseInput,
): Promise<{ orderId: string; lineId: string }> {
  const [newOrder] = await db
    .insert(order)
    .values({
      buyerUserId: input.buyerUserId,
      status: input.orderStatus,
      currency: 'ILS',
      priceMode: 'inclusive',
      subtotal: input.amountAgorot,
      tax: BigInt(0),
      discount: BigInt(0),
      total: input.amountAgorot,
      idempotencyKey: input.idempotencyKey,
      requestHash: input.requestHash,
      createdAt: input.orderCreatedAt,
    })
    .returning({ id: order.id });

  const [newLine] = await db
    .insert(orderLine)
    .values({
      orderId: newOrder!.id,
      variantId: input.variantId,
      kind: 'voucher',
      qty: 1,
      unitPrice: input.amountAgorot,
      lineTotal: input.amountAgorot,
      vendorId: input.vendorId,
    })
    .returning({ id: orderLine.id });

  await createVoucher(db, {
    id: input.voucherId,
    orderId: newOrder!.id,
    lineId: newLine!.id,
    unitIndex: 0,
    vendorId: input.vendorId,
    state: input.redemptionStatus,
    expiresAt: input.expiresAt,
    redeemedAt: input.redeemedAt,
  });
  await createVoucherExtension(db, {
    voucherId: input.voucherId,
    lineId: newLine!.id,
    qrTokenHash: input.qrTokenHash,
    reviewEligible: input.reviewEligible,
  });

  return { orderId: newOrder!.id, lineId: newLine!.id };
}
