import { sql, type SQL } from 'drizzle-orm';
import { deals, dealTranslations } from '@/server/db/schema';

/**
 * Shape of a deal object sufficient for the in-memory visibility check.
 * `translations` is the preloaded sidecar array (populated by a JOIN or eager load).
 */
export interface DealLike {
  dealState: string;
  sourceLanguage: string;
  translations?: Array<{
    locale: string;
    status: string;
    title: string;
    description: string;
  }>;
}

/**
 * Synchronous in-memory visibility predicate.
 *
 * A deal is visible to a customer requesting `locale` when:
 *   1. dealState === 'APPROVED'
 *   2. locale matches the deal's source language (no translation needed), OR
 *      a translation exists for that locale with status 'OK' and non-empty title + description.
 */
export function isVisibleToCustomer(deal: DealLike, locale: string): boolean {
  if (deal.dealState !== 'ACTIVE') return false;
  if (locale === deal.sourceLanguage) return true;
  const t = (deal.translations ?? []).find((x) => x.locale === locale);
  if (!t) return false;
  if (t.status !== 'OK') return false;
  if (!t.title || !t.description) return false;
  return true;
}

/**
 * Drizzle SQL fragment for use in WHERE clauses on deal list queries.
 *
 * Usage:
 *   db.select().from(deals).where(dealsVisibleWhere(locale))
 *
 * Equivalent logic:
 *   deals.dealState = 'APPROVED'
 *   AND (
 *     deals.sourceLanguage = $locale
 *     OR EXISTS (
 *       SELECT 1 FROM deal_translations
 *       WHERE deal_id = deals.id
 *         AND locale = $locale
 *         AND status = 'OK'
 *         AND title <> ''
 *         AND description <> ''
 *     )
 *   )
 */
export function dealsVisibleWhere(locale: string): SQL {
  return sql`
    ${deals.dealState} = 'ACTIVE'
    AND (
      ${deals.sourceLanguage} = ${locale}
      OR EXISTS (
        SELECT 1 FROM ${dealTranslations}
        WHERE ${dealTranslations.dealId} = ${deals.id}
          AND ${dealTranslations.locale} = ${locale}
          AND ${dealTranslations.status} = 'OK'
          AND ${dealTranslations.title} <> ''
          AND ${dealTranslations.description} <> ''
      )
    )
  `;
}
