// app/(public)/participar/page.tsx
// The purchase-flow entry (agent B). Server component: it fetches the active
// raffle config + pricing tiers, reads the Turnstile site key server-side
// (TURNSTILE_SITE_KEY is NOT a NEXT_PUBLIC var, so a server component must read
// it and pass it down), captures UTM/influencer attribution silently from the
// URL (no field shown), and renders the client <PurchaseFlow>.
//
// Money + crypto are not touched here, but this reads env + DB, so it must run
// on the Node runtime, not Edge.

import * as React from "react";
import Link from "next/link";
import { and, asc, eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { pricingTiers, raffles } from "@/lib/db/schema";
import { Button, Card } from "@/components/ui";
import { PurchaseFlow } from "@/components/flow/PurchaseFlow";
import type {
  FlowAttribution,
  FlowRaffle,
  PublicPricingTier,
} from "@/components/flow/types";

export const runtime = "nodejs";
// Always render fresh: raffle status + tiers are config that can change, and the
// page reads request-scoped UTM params.
export const dynamic = "force-dynamic";

interface LoadResult {
  raffle: FlowRaffle | null;
  tiers: PublicPricingTier[];
}

/** Load the raffle the buyer should participate in. Preference: a raffle the
 *  ?evento=<slug> param names AND that is open; otherwise the single open
 *  raffle. Returns null when no raffle is open (honest empty state). */
async function loadActiveRaffle(slug?: string): Promise<LoadResult> {
  try {
    const where = slug
      ? and(eq(raffles.slug, slug), eq(raffles.status, "open"))
      : eq(raffles.status, "open");

    const rows = await db
      .select()
      .from(raffles)
      .where(where)
      .orderBy(asc(raffles.opensAt))
      .limit(1);

    const row = rows[0];
    if (!row) return { raffle: null, tiers: [] };

    const tierRows = await db
      .select()
      .from(pricingTiers)
      .where(eq(pricingTiers.raffleId, row.id))
      .orderBy(asc(pricingTiers.sortOrder));

    const raffle: FlowRaffle = {
      id: row.id,
      slug: row.slug,
      name: row.name,
      basePriceCents: row.basePriceCents,
      maxChancesPerPurchase: row.maxChancesPerPurchase,
      feeOptInEnabled: row.feeOptInEnabled,
      basesUrl: row.basesUrl,
      // termsVersion is frozen in the bases; until a dedicated column exists we
      // bind it to the raffle slug so the participant row records WHICH terms
      // were accepted. Agent C echoes this back through register.
      termsVersion: `bases-${row.slug}`,
    };

    const tiers: PublicPricingTier[] = tierRows.map((t) => ({
      id: t.id,
      label: t.label,
      extraChances: t.extraChances,
      extraPriceCents: t.extraPriceCents,
      sortOrder: t.sortOrder,
    }));

    return { raffle, tiers };
  } catch {
    // DB unavailable (build time / outage). Render the honest unavailable state
    // rather than crashing the route.
    return { raffle: null, tiers: [] };
  }
}

function firstParam(v: string | string[] | undefined): string | undefined {
  if (Array.isArray(v)) return v[0];
  return v;
}

export default async function ParticiparPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const eventoSlug = firstParam(params.evento);
  const { raffle, tiers } = await loadActiveRaffle(eventoSlug);

  if (!raffle) {
    return (
      <div className="mx-auto flex w-full max-w-[480px] flex-col gap-md px-5 py-12">
        <Card elevation="tight">
          <h1 className="font-display text-heading-lg text-ink-strong">
            La rifa no está abierta en este momento
          </h1>
          <p className="mt-2 font-body text-body-md text-muted">
            Vuelve pronto. Cuando la rifa esté activa, podrás inscribirte y
            elegir tus chances desde aquí.
          </p>
          <div className="mt-4">
            <Link href="/" className="block">
              <Button type="button" variant="secondary" block>
                Volver al inicio
              </Button>
            </Link>
          </div>
        </Card>
      </div>
    );
  }

  const attribution: FlowAttribution = {
    utmSource: firstParam(params.utm_source),
    utmCampaign: firstParam(params.utm_campaign),
    influencerCode: firstParam(params.ref) ?? firstParam(params.influencer),
  };

  return (
    <PurchaseFlow raffle={raffle} tiers={tiers} attribution={attribution} />
  );
}

export const metadata = {
  title: "Participa en la rifa de Teletón Perú",
  description:
    "Inscríbete, elige tus chances y participa en la rifa de Teletón. Tu ayuda también te ayuda a ti.",
};
