/**
 * Tunisie Pronostic — Cloud Functions (Firebase, Node 20, TypeScript)
 *
 * 1. importFixtures  (callable, admin only)  → pull matches of ANY league from API-Football into Firestore
 * 2. syncLiveMatches (every 5 min)           → update status/score of started matches, settle predictions at full time
 * 3. refreshUpcoming (every 6 hours)         → catch postponed / rescheduled kickoffs
 *
 * The phone app NEVER calls API-Football directly: the API key stays secret and the
 * daily quota is shared by all users through Firestore.
 *
 * Setup:
 *   firebase functions:secrets:set API_FOOTBALL_KEY
 *   firebase deploy --only functions,firestore:rules,firestore:indexes
 */
import { initializeApp } from "firebase-admin/app";
import { getFirestore, FieldValue, Timestamp, WriteBatch } from "firebase-admin/firestore";
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { onSchedule } from "firebase-functions/v2/scheduler";
import { defineSecret } from "firebase-functions/params";
import * as logger from "firebase-functions/logger";

initializeApp();
const db = getFirestore();
const API_KEY = defineSecret("API_FOOTBALL_KEY");
const API_BASE = "https://v3.football.api-sports.io";
const REGION = "europe-west1"; // closest to Tunisia

// ---- Scoring rules (change here) ------------------------------------------
const COUPONS_CORRECT_OUTCOME = 1; // right 1 / X / 2
const COUPONS_EXACT_SCORE = 3;     // right exact score (replaces the 1 above)

// ---- API-Football status codes → app status --------------------------------
type MatchStatus = "scheduled" | "live" | "finished" | "postponed" | "cancelled";

function mapStatus(short: string): MatchStatus {
  if (["NS", "TBD"].includes(short)) return "scheduled";
  if (["1H", "HT", "2H", "ET", "BT", "P", "SUSP", "INT", "LIVE"].includes(short)) return "live";
  if (["FT", "AET", "PEN"].includes(short)) return "finished";
  if (["PST"].includes(short)) return "postponed";
  return "cancelled"; // CANC, ABD, AWD, WO
}

async function apiGet(path: string, params: Record<string, string | number>): Promise<any[]> {
  const qs = new URLSearchParams(Object.entries(params).map(([k, v]) => [k, String(v)]));
  const res = await fetch(`${API_BASE}${path}?${qs}`, {
    headers: { "x-apisports-key": API_KEY.value() },
  });
  if (!res.ok) throw new Error(`API-Football ${res.status}`);
  const body = await res.json();
  const errors = body.errors;
  if (errors && (Array.isArray(errors) ? errors.length : Object.keys(errors).length)) {
    throw new Error(`API-Football error: ${JSON.stringify(errors)}`);
  }
  return body.response ?? [];
}

/** Firestore document built from one API-Football fixture. */
function fixtureToDoc(f: any) {
  const status = mapStatus(f.fixture.status.short);
  // Predictions are judged on the 90-minute score (extra time & penalties ignored).
  const ft = f.score?.fulltime;
  const live = f.goals;
  const score =
    status === "finished" && ft?.home != null
      ? { home: ft.home, away: ft.away }
      : live?.home != null
      ? { home: live.home, away: live.away }
      : null;

  return {
    fixtureId: f.fixture.id,
    kickoff: Timestamp.fromMillis(f.fixture.timestamp * 1000),
    status,
    statusShort: f.fixture.status.short,
    elapsed: f.fixture.status.elapsed ?? null,
    score,
    league: {
      id: f.league.id,
      name: f.league.name,
      country: f.league.country,
      logo: f.league.logo,
      round: f.league.round,
    },
    home: { id: f.teams.home.id, name: f.teams.home.name, logo: f.teams.home.logo },
    away: { id: f.teams.away.id, name: f.teams.away.name, logo: f.teams.away.logo },
    updatedAt: FieldValue.serverTimestamp(),
  };
}

// ============================================================================
// 1) Admin: import matches from ANY league
//    data: { leagueId: 202, season: 2026, from: "2026-11-21", to: "2026-11-30" }
//    (find league IDs with GET /leagues?country=Tunisia or ?search=premier)
// ============================================================================
export const importFixtures = onCall(
  { region: REGION, secrets: [API_KEY] },
  async (req) => {
    if (req.auth?.token.admin !== true) {
      throw new HttpsError("permission-denied", "Admin only");
    }
    const { leagueId, season, from, to } = req.data ?? {};
    if (!leagueId || !season || !from || !to) {
      throw new HttpsError("invalid-argument", "leagueId, season, from, to are required");
    }

    const fixtures = await apiGet("/fixtures", {
      league: leagueId, season, from, to, timezone: "Africa/Tunis",
    });

    const batch = db.batch();
    let imported = 0;
    for (const f of fixtures) {
      const doc = fixtureToDoc(f);
      if (doc.status !== "scheduled") continue; // only future matches can be predicted
      batch.set(
        db.doc(`matches/${f.fixture.id}`),
        { ...doc, published: true, settled: false, createdAt: FieldValue.serverTimestamp() },
        { merge: true },
      );
      imported++;
    }
    await batch.commit();
    logger.info(`Imported ${imported} fixtures for league ${leagueId}`);
    return { imported };
  },
);

// ============================================================================
// 1b) Admin web page: list ALL matches of a day (every league) + publish picks
// ============================================================================
const TUNIS_OFFSET = "+01:00"; // Tunisia: UTC+1, no daylight saving

function requireAdmin(req: { auth?: { token: Record<string, any> } }) {
  if (req.auth?.token.admin !== true) throw new HttpsError("permission-denied", "Admin only");
}

/** Plain JSON version of a fixture (stored in the cache, sent to the web page). */
function fixtureSummary(f: any) {
  return {
    id: f.fixture.id,
    kickoffMs: f.fixture.timestamp * 1000,
    status: mapStatus(f.fixture.status.short),
    statusShort: f.fixture.status.short,
    league: {
      id: f.league.id, name: f.league.name, country: f.league.country,
      logo: f.league.logo, round: f.league.round, season: f.league.season,
    },
    home: { id: f.teams.home.id, name: f.teams.home.name, logo: f.teams.home.logo },
    away: { id: f.teams.away.id, name: f.teams.away.name, logo: f.teams.away.logo },
  };
}

/**
 * data: { date: "2026-11-21", refresh?: boolean }
 * Uses ONE API request per day (/fixtures?date=...), cached in
 * fixtureCache/{date}/leagues/{leagueId} so reloading the page is free.
 */
export const listFixturesByDate = onCall(
  { region: REGION, secrets: [API_KEY], memory: "512MiB" },
  async (req) => {
    requireAdmin(req);
    const date = String(req.data?.date ?? "");
    if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpsError("invalid-argument", "date = YYYY-MM-DD");

    const cacheRef = db.doc(`fixtureCache/${date}`);
    const meta = await cacheRef.get();
    let fixtures: any[] = [];

    if (meta.exists && !req.data?.refresh) {
      const leagues = await cacheRef.collection("leagues").get();
      leagues.forEach((d) => fixtures.push(...(d.data().fixtures as any[])));
    } else {
      const raw = await apiGet("/fixtures", { date, timezone: "Africa/Tunis" });
      fixtures = raw.map(fixtureSummary);
      // Group by league → one small doc per league (stays far below the 1 MB doc limit).
      const byLeague = new Map<number, any[]>();
      for (const f of fixtures) {
        if (!byLeague.has(f.league.id)) byLeague.set(f.league.id, []);
        byLeague.get(f.league.id)!.push(f);
      }
      const old = await cacheRef.collection("leagues").get();
      let batch = db.batch(); let n = 0;
      const flush = async () => { await batch.commit(); batch = db.batch(); n = 0; };
      for (const d of old.docs) { batch.delete(d.ref); if (++n >= 450) await flush(); }
      for (const [leagueId, list] of byLeague) {
        batch.set(cacheRef.collection("leagues").doc(String(leagueId)), { fixtures: list });
        if (++n >= 450) await flush();
      }
      batch.set(cacheRef, { fetchedAt: FieldValue.serverTimestamp(), count: fixtures.length });
      await flush();
    }

    // Which of these are already published?
    const start = Timestamp.fromDate(new Date(`${date}T00:00:00${TUNIS_OFFSET}`));
    const end = Timestamp.fromDate(new Date(`${date}T23:59:59${TUNIS_OFFSET}`));
    const pub = await db.collection("matches")
      .where("kickoff", ">=", start).where("kickoff", "<=", end).get();
    const published = pub.docs.filter((d) => d.data().published === true).map((d) => Number(d.id));

    const fetchedAt = (await cacheRef.get()).data()?.fetchedAt?.toMillis() ?? Date.now();
    return { fixtures, published, fetchedAt };
  },
);

/** data: { date: "2026-11-21", ids: [123, 456] } — publishes from the cache, no API request. */
export const publishFixtures = onCall({ region: REGION }, async (req) => {
  requireAdmin(req);
  const date = String(req.data?.date ?? "");
  const ids: number[] = (req.data?.ids ?? []).map(Number);
  if (!ids.length) throw new HttpsError("invalid-argument", "ids required");

  const leagues = await db.collection(`fixtureCache/${date}/leagues`).get();
  const wanted = new Set(ids);
  const batch = db.batch();
  let published = 0;
  const skipped: number[] = [];
  leagues.forEach((d) => {
    for (const f of d.data().fixtures as any[]) {
      if (!wanted.has(f.id)) continue;
      if (f.status !== "scheduled" || f.kickoffMs <= Date.now()) { skipped.push(f.id); continue; }
      batch.set(db.doc(`matches/${f.id}`), {
        fixtureId: f.id,
        kickoff: Timestamp.fromMillis(f.kickoffMs),
        status: "scheduled",
        statusShort: f.statusShort,
        elapsed: null,
        score: null,
        league: { id: f.league.id, name: f.league.name, country: f.league.country,
                  logo: f.league.logo, round: f.league.round },
        home: f.home,
        away: f.away,
        published: true,
        settled: false,
        createdAt: FieldValue.serverTimestamp(),
        updatedAt: FieldValue.serverTimestamp(),
      }, { merge: true });
      published++;
    }
  });
  await batch.commit();
  return { published, skipped };
});

/** data: { id: 123 } — hide a match from the app (only before kickoff). */
export const unpublishFixture = onCall({ region: REGION }, async (req) => {
  requireAdmin(req);
  const ref = db.doc(`matches/${Number(req.data?.id)}`);
  const snap = await ref.get();
  if (!snap.exists) throw new HttpsError("not-found", "Match not found");
  if ((snap.data()!.kickoff as Timestamp).toMillis() <= Date.now()) {
    throw new HttpsError("failed-precondition", "Match already started");
  }
  // status "hidden" → ignored by the sync jobs and blocked by the prediction rules.
  await ref.update({ published: false, status: "hidden" });
  // Remove predictions already made on it (nobody gets coupons for a hidden match).
  const preds = await db.collection("predictions").where("matchId", "==", ref.id).get();
  const batch = db.batch();
  preds.forEach((p) => batch.delete(p.ref));
  await batch.commit();
  return { ok: true, removedPredictions: preds.size };
});

// ============================================================================
// 2) Every 5 minutes: update matches that have kicked off, settle finished ones
// ============================================================================
export const syncLiveMatches = onSchedule(
  { region: REGION, schedule: "every 5 minutes", timeZone: "Africa/Tunis", secrets: [API_KEY] },
  async () => {
    // Matches that should have started but aren't finished yet.
    const snap = await db.collection("matches")
      .where("status", "in", ["scheduled", "live"])
      .where("kickoff", "<=", Timestamp.now())
      .get();
    if (snap.empty) return; // no API call → no quota used

    const ids = snap.docs.map((d) => d.id);
    // API-Football accepts up to 20 fixture ids per request.
    for (let i = 0; i < ids.length; i += 20) {
      const chunk = ids.slice(i, i + 20);
      const fixtures = await apiGet("/fixtures", { ids: chunk.join("-") });
      for (const f of fixtures) {
        const doc = fixtureToDoc(f);
        const ref = db.doc(`matches/${f.fixture.id}`);
        await ref.set(doc, { merge: true });
        if (doc.status === "finished" && doc.score) {
          await settleMatch(ref.id, doc.score);
        } else if (doc.status === "cancelled") {
          await voidMatch(ref.id);
        }
      }
    }
  },
);

// ============================================================================
// 3) Every 6 hours: refresh kickoff times of upcoming matches (postponements)
// ============================================================================
export const refreshUpcoming = onSchedule(
  { region: REGION, schedule: "every 6 hours", timeZone: "Africa/Tunis", secrets: [API_KEY] },
  async () => {
    const snap = await db.collection("matches")
      .where("status", "in", ["scheduled", "postponed"])
      .get();
    const ids = snap.docs.map((d) => d.id);
    for (let i = 0; i < ids.length; i += 20) {
      const fixtures = await apiGet("/fixtures", { ids: ids.slice(i, i + 20).join("-") });
      const batch = db.batch();
      for (const f of fixtures) {
        batch.set(db.doc(`matches/${f.fixture.id}`), fixtureToDoc(f), { merge: true });
      }
      await batch.commit();
    }
  },
);

// ============================================================================
// Settlement — idempotent: only predictions with settled == false are touched,
// and each prediction is marked settled in the SAME batch that adds its coupons.
// ============================================================================
function outcome(h: number, a: number): "1" | "X" | "2" {
  return h > a ? "1" : h < a ? "2" : "X";
}

/** Week id used by the weekly draw, e.g. "2026-W47" (ISO week). */
function isoWeekId(d = new Date()): string {
  const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
  const day = t.getUTCDay() || 7;
  t.setUTCDate(t.getUTCDate() + 4 - day);
  const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
  const week = Math.ceil(((t.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
  return `${t.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
}

async function settleMatch(matchId: string, score: { home: number; away: number }) {
  const result = outcome(score.home, score.away);
  const weekId = isoWeekId();

  while (true) {
    const page = await db.collection("predictions")
      .where("matchId", "==", matchId)
      .where("settled", "==", false)
      .limit(150) // 3 writes per prediction → stays under the 500-write batch limit
      .get();
    if (page.empty) break;

    const batch: WriteBatch = db.batch();
    for (const p of page.docs) {
      const pr = p.data();
      const exact = pr.homeGoals === score.home && pr.awayGoals === score.away;
      const coupons = exact
        ? COUPONS_EXACT_SCORE
        : pr.pick === result ? COUPONS_CORRECT_OUTCOME : 0;

      batch.update(p.ref, {
        settled: true,
        result: exact ? "exact" : coupons > 0 ? "won" : "lost",
        coupons,
        settledAt: FieldValue.serverTimestamp(),
      });
      if (coupons > 0) {
        batch.set(db.doc(`users/${pr.uid}`), { coupons: FieldValue.increment(coupons) }, { merge: true });
        batch.set(
          db.doc(`draws/${weekId}/entries/${pr.uid}`),
          { uid: pr.uid, coupons: FieldValue.increment(coupons) },
          { merge: true },
        );
      }
    }
    await batch.commit();
  }
  await db.doc(`matches/${matchId}`).update({ settled: true });
}

async function voidMatch(matchId: string) {
  while (true) {
    const page = await db.collection("predictions")
      .where("matchId", "==", matchId).where("settled", "==", false).limit(400).get();
    if (page.empty) break;
    const batch = db.batch();
    page.docs.forEach((p) => batch.update(p.ref, { settled: true, result: "void", coupons: 0 }));
    await batch.commit();
  }
  await db.doc(`matches/${matchId}`).update({ settled: true });
}
