import { database } from "~/database/context";
import * as schema from "~/database/schema";
import { eq } from "drizzle-orm";

/**
 * Check if a season is complete
 * A season is considered complete if:
 * 1. The season status is "completed"
 * OR
 * 2. All participants in all sports seasons have final results
 */
export async function isSeasonComplete(
  seasonId: string,
  providedDb?: ReturnType<typeof database>
): Promise<boolean> {
  const db = providedDb || database();

  // Check season status first (simplest check)
  const season = await db.query.seasons.findFirst({
    where: eq(schema.seasons.id, seasonId),
  });

  if (!season) {
    return false;
  }

  if (season.status === "completed") {
    return true;
  }

  // If status is not completed, check if all participants have results
  // Get all sports seasons for this season
  const seasonSports = await db.query.seasonSports.findMany({
    where: eq(schema.seasonSports.seasonId, seasonId),
  });

  if (seasonSports.length === 0) {
    return false;
  }

  // Get all draft picks for this season with participant info
  const allPicks = await db.query.draftPicks.findMany({
    where: eq(schema.draftPicks.seasonId, seasonId),
    with: {
      participant: {
        with: {
          results: true,
        },
      },
    },
  });

  // Check if all drafted participants have results
  for (const pick of allPicks) {
    // If any drafted participant doesn't have a result, season is not complete
    if (!pick.participant.results || pick.participant.results.length === 0) {
      return false;
    }
  }

  return true;
}

/**
 * Get the completion percentage of a season
 * Returns a value between 0 and 100
 */
export async function getSeasonCompletionPercentage(
  seasonId: string,
  providedDb?: ReturnType<typeof database>
): Promise<number> {
  const db = providedDb || database();

  // Get all draft picks for this season with participant results
  const allPicks = await db.query.draftPicks.findMany({
    where: eq(schema.draftPicks.seasonId, seasonId),
    with: {
      participant: {
        with: {
          results: true,
        },
      },
    },
  });

  if (allPicks.length === 0) {
    return 0;
  }

  // Count how many have results
  const completedCount = allPicks.filter(
    (pick) => pick.participant.results && pick.participant.results.length > 0
  ).length;

  return Math.round((completedCount / allPicks.length) * 100);
}
