/**
 * Group tier queries - typed async functions for the group_tiers table.
 */

import { eq, asc, desc } from 'drizzle-orm';
import type { DrizzleClient } from '../client.js';
import { groupTiers } from '../schema.js';

// ─── Read helpers ─────────────────────────────────────────────────────────────

/**
 * Returns all tiers for a group deal, sorted by sortOrder ascending (cheapest tiers first).
 */
export async function findByGroupDealId(db: DrizzleClient, groupDealId: string) {
  return db
    .select()
    .from(groupTiers)
    .where(eq(groupTiers.groupDealId, groupDealId))
    .orderBy(asc(groupTiers.sortOrder));
}

/**
 * Returns the highest applicable tier for the given participant count.
 * "Highest" means the tier with the largest minParticipants that is still <= participantCount.
 * Returns null if no tier applies (participantCount < all minParticipants).
 */
export async function getApplicableTier(
  db: DrizzleClient,
  groupDealId: string,
  participantCount: number,
) {
  // Fetch all tiers ordered by minParticipants descending, then find the first
  // one whose minParticipants <= participantCount (i.e. highest qualifying tier).
  const allTiers = await db
    .select()
    .from(groupTiers)
    .where(eq(groupTiers.groupDealId, groupDealId))
    .orderBy(desc(groupTiers.minParticipants));

  return allTiers.find((t) => t.minParticipants <= participantCount) ?? null;
}

// ─── Write helpers ────────────────────────────────────────────────────────────

export type TierInput = {
  minParticipants: number;
  pricePerUnit: string;
  discountPercent?: number;
  sortOrder?: number;
};

/**
 * Inserts multiple tier rows for a group deal in a single batch insert.
 */
export async function createMany(db: DrizzleClient, groupDealId: string, tiers: TierInput[]) {
  if (tiers.length === 0) return [];
  return db
    .insert(groupTiers)
    .values(
      tiers.map((t, i) => ({
        groupDealId,
        minParticipants: t.minParticipants,
        pricePerUnit: t.pricePerUnit,
        discountPercent: t.discountPercent ?? 50,
        sortOrder: t.sortOrder ?? i,
      })),
    )
    .returning();
}
