import "server-only";
import type { RowDataPacket } from "mysql2";
import { getDb, isDatabaseConfigured } from "@/lib/db";
import { type Horse } from "@/lib/types";

export type { Horse } from "@/lib/types";
export { MONTHLY_TOP_NAMES } from "@/lib/types";

interface SearchRow extends RowDataPacket {
  id: number;
  name: string;
  category: Horse["category"];
}

export async function searchHorses(searchTerm: string): Promise<Horse[]> {
  const term = searchTerm.trim();
  if (term.length < 2) {
    return [];
  }

  if (!isDatabaseConfigured()) {
    return [];
  }

  try {
    const db = getDb();
    const pattern = `%${term}%`;

    const [rows] = await db.query<SearchRow[]>(
      `
      SELECT id, name, category
      FROM (
        SELECT
          id,
          \`nom(pays)\` AS name,
          'Carrière de Course' AS category
        FROM data_ifce_v2
        WHERE \`nom(pays)\` LIKE ?

        UNION ALL

        SELECT
          id,
          \`nom_mère(pays)\` AS name,
          'Jument' AS category
        FROM mare_details
        WHERE \`nom_mère(pays)\` LIKE ?

        UNION ALL

        SELECT
          id,
          name,
          'Etalon' AS category
        FROM stallion
        WHERE name LIKE ?
      ) AS search_results
      ORDER BY 
        CASE 
          WHEN name LIKE ? THEN 1 
          ELSE 2 
        END,
        name ASC
      LIMIT 25
      `,
      [pattern, pattern, pattern, `${term}%`]
    );

    return rows.map((row) => {
      // Deterministic calculation based on id & name for rating presentation
      const hash = Array.from(row.name).reduce((acc, c) => acc + c.charCodeAt(0), row.id);
      const calculatedGrade = Number((8.2 + (hash % 17) / 10).toFixed(1)); // 8.2 - 9.8
      const calculatedStars = Number((3.5 + ((hash % 4) * 0.5)).toFixed(1)); // 3.5 - 5.0
      const isActive = (hash % 6) !== 0;

      const discipline =
        row.category === "Jument"
          ? "Poulinière"
          : row.category === "Carrière de Course"
          ? "Élevage & Course"
          : "Trot attelé";

      const ranking =
        row.category === "Etalon"
          ? (calculatedGrade >= 9.5 ? "Étalon de référence" : "Étalon agréé")
          : row.category === "Jument"
          ? "Poulinière confirmée"
          : "Trotteur en course";

      return {
        id: row.id,
        name: row.name.toUpperCase(),
        category: row.category,
        grade: calculatedGrade,
        stars: calculatedStars,
        active: isActive,
        breed: "Trotteur Français",
        year: 2012 + (hash % 12),
        discipline,
        ranking,
        image: "/horses/horse-portrait.svg",
        statistics: [
          { label: "Indice performance", value: `${100 + (hash % 28)} %` },
          { label: "Produits / Fratrie", value: `${Math.max(1, hash % 520)}` },
          { label: "Note modèle & allures", value: `${calculatedGrade} / 10` },
          { label: "Statut FoalX", value: isActive ? "Vérifié & Actif" : "Archivé" }
        ]
      };
    });
  } catch (error) {
    console.error("[Search] Database query failed:", error);
    return [];
  }
}
