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

export type SportsSeason = typeof schema.sportsSeasons.$inferSelect;
export type NewSportsSeason = typeof schema.sportsSeasons.$inferInsert;
export type SportsSeasonWithSport = SportsSeason & {
  sport: typeof schema.sports.$inferSelect;
};
export type SportsSeasonStatus = "upcoming" | "active" | "completed";
export type ScoringType = "playoffs" | "regular_season" | "majors";

export async function createSportsSeason(data: NewSportsSeason): Promise<SportsSeason> {
  const db = database();
  const [sportsSeason] = await db
    .insert(schema.sportsSeasons)
    .values(data)
    .returning();
  return sportsSeason;
}

export async function findSportsSeasonById(id: string): Promise<SportsSeasonWithSport | undefined> {
  const db = database();
  return await db.query.sportsSeasons.findFirst({
    where: eq(schema.sportsSeasons.id, id),
    with: {
      sport: true,
    },
  }) as SportsSeasonWithSport | undefined;
}

export async function findSportsSeasonsBySportId(sportId: string): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    where: eq(schema.sportsSeasons.sportId, sportId),
    orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
    with: {
      sport: true,
    },
  });
}

export async function findActiveSportsSeasonsBySportId(sportId: string): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    where: (ss, { and }) =>
      and(
        eq(ss.sportId, sportId),
        eq(ss.status, "active")
      ),
    orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
    with: {
      sport: true,
    },
  });
}

export async function findSportsSeasonsByYear(year: number): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    where: eq(schema.sportsSeasons.year, year),
    orderBy: (sportsSeasons, { asc }) => [asc(sportsSeasons.name)],
    with: {
      sport: true,
    },
  });
}

export async function findSportsSeasonsByStatus(status: SportsSeasonStatus): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    where: eq(schema.sportsSeasons.status, status),
    orderBy: (sportsSeasons, { desc }) => [desc(sportsSeasons.year)],
    with: {
      sport: true,
    },
  });
}

export async function findAllSportsSeasons(): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    orderBy: (sportsSeasons, { desc, asc }) => [desc(sportsSeasons.year), asc(sportsSeasons.name)],
    with: {
      sport: true,
      participants: {
        columns: {
          id: true,
        },
      },
    },
  });
}

export async function findDraftableSportsSeasons(): Promise<SportsSeason[]> {
  const db = database();
  return await db.query.sportsSeasons.findMany({
    where: eq(schema.sportsSeasons.isDraftable, true),
    orderBy: (sportsSeasons, { desc, asc }) => [desc(sportsSeasons.year), asc(sportsSeasons.name)],
    with: {
      sport: true,
    },
  });
}

export async function updateSportsSeason(
  id: string,
  data: Partial<NewSportsSeason>
): Promise<SportsSeason> {
  const db = database();
  const [sportsSeason] = await db
    .update(schema.sportsSeasons)
    .set({ ...data, updatedAt: new Date() })
    .where(eq(schema.sportsSeasons.id, id))
    .returning();
  return sportsSeason;
}

export async function updateSportsSeasonStatus(
  id: string,
  status: SportsSeasonStatus
): Promise<SportsSeason> {
  return await updateSportsSeason(id, { status });
}

export async function deleteSportsSeason(id: string): Promise<void> {
  const db = database();
  await db.delete(schema.sportsSeasons).where(eq(schema.sportsSeasons.id, id));
}

export async function copyParticipantsFromPreviousSeason(
  currentSeasonId: string,
  previousSeasonId: string
): Promise<void> {
  const db = database();
  
  // Get all participants from previous season
  const previousParticipants = await db.query.participants.findMany({
    where: eq(schema.participants.sportsSeasonId, previousSeasonId),
  });

  // Insert them into the current season
  if (previousParticipants.length > 0) {
    await db.insert(schema.participants).values(
      previousParticipants.map((p) => ({
        sportsSeasonId: currentSeasonId,
        name: p.name,
        shortName: p.shortName,
        externalId: p.externalId,
        expectedValue: p.expectedValue,
      }))
    );
  }
}
