/**
 * Deal-category → statutory-exemption mapping (Cancellation Regulations 5771-2010).
 * Owner decision (g_legal): perishable food-service categories are exempt from the
 * 14-day change-of-mind right; packaged shelf-stable goods are not.
 */
import { eq } from 'drizzle-orm';
import type { DrizzleClient } from '@/server/db/client.js';
import { dealCategories } from '@/server/db/schema.js';

/** Category slugs exempt under 5771-2010 perishable-goods rules for this marketplace. */
export const STATUTORY_EXEMPT_DEAL_CATEGORY_SLUGS = [
  'meal',
  'bakery',
  'beverage',
  'dessert',
] as const;

export type StatutoryExemptDealCategorySlug = (typeof STATUTORY_EXEMPT_DEAL_CATEGORY_SLUGS)[number];

const EXEMPT_SLUG_SET = new Set<string>(STATUTORY_EXEMPT_DEAL_CATEGORY_SLUGS);

export function isDealCategoryStatutoryExempt(categorySlug: string | null | undefined): boolean {
  return categorySlug != null && EXEMPT_SLUG_SET.has(categorySlug);
}

export async function resolveDealCategorySlug(
  db: DrizzleClient,
  categoryId: string | null | undefined,
): Promise<string | null> {
  if (!categoryId) return null;
  const [row] = await db
    .select({ slug: dealCategories.slug })
    .from(dealCategories)
    .where(eq(dealCategories.id, categoryId))
    .limit(1);
  return row?.slug ?? null;
}

export async function isDealCategoryStatutoryExemptById(
  db: DrizzleClient,
  categoryId: string | null | undefined,
): Promise<boolean> {
  const slug = await resolveDealCategorySlug(db, categoryId);
  return isDealCategoryStatutoryExempt(slug);
}
