import { and, eq } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client';
import { dealSkus } from '@/server/db/schema';
import { hashOptionIds } from './hash';
import type { SkuRow } from './read';

export type ValidateResult =
  | { ok: true; sku: SkuRow }
  | { ok: false; code: 'SKU_NOT_FOUND' | 'SKU_INACTIVE' | 'SKU_OUT_OF_STOCK'; message: string };

export async function validateSkuSelection(
  db: DrizzleClient,
  args: { dealId: string; optionIds: string[]; qty: number },
): Promise<ValidateResult> {
  const hash = hashOptionIds(args.optionIds);
  const rows = await db
    .select()
    .from(dealSkus)
    .where(and(eq(dealSkus.dealId, args.dealId), eq(dealSkus.optionIdsHash, hash)));
  if (rows.length === 0) {
    return { ok: false, code: 'SKU_NOT_FOUND', message: `No SKU for deal ${args.dealId} combo ${hash}` };
  }
  const sku = { ...rows[0]!, qtyTiers: [] as { minQty: number; discountPercent: number }[] } as SkuRow;
  if (!sku.isActive) {
    return { ok: false, code: 'SKU_INACTIVE', message: `SKU ${sku.id} inactive` };
  }
  const available = sku.quantityTotal - sku.quantitySold;
  if (available < args.qty) {
    return { ok: false, code: 'SKU_OUT_OF_STOCK', message: `SKU ${sku.id} has ${available} left` };
  }
  return { ok: true, sku };
}
