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

export type SeasonTemplate = typeof schema.seasonTemplates.$inferSelect;
export type NewSeasonTemplate = typeof schema.seasonTemplates.$inferInsert;

export async function createSeasonTemplate(data: NewSeasonTemplate): Promise<SeasonTemplate> {
  const db = database();
  const [template] = await db
    .insert(schema.seasonTemplates)
    .values(data)
    .returning();
  return template;
}

export async function findSeasonTemplateById(id: string): Promise<SeasonTemplate | undefined> {
  const db = database();
  return await db.query.seasonTemplates.findFirst({
    where: eq(schema.seasonTemplates.id, id),
  });
}

export async function findSeasonTemplateWithSportsSeasons(id: string) {
  const db = database();
  return await db.query.seasonTemplates.findFirst({
    where: eq(schema.seasonTemplates.id, id),
    with: {
      seasonTemplateSports: {
        with: {
          sportsSeason: {
            with: {
              sport: true,
            },
          },
        },
      },
    },
  });
}

export async function findActiveSeasonTemplates(): Promise<SeasonTemplate[]> {
  const db = database();
  return await db.query.seasonTemplates.findMany({
    where: eq(schema.seasonTemplates.isActive, true),
    orderBy: (templates, { desc }) => [desc(templates.year)],
  });
}

export async function findSeasonTemplatesByYear(year: number): Promise<SeasonTemplate[]> {
  const db = database();
  return await db.query.seasonTemplates.findMany({
    where: eq(schema.seasonTemplates.year, year),
    orderBy: (templates, { asc }) => [asc(templates.name)],
  });
}

export async function findAllSeasonTemplates(): Promise<SeasonTemplate[]> {
  const db = database();
  return await db.query.seasonTemplates.findMany({
    orderBy: (templates, { desc }) => [desc(templates.year)],
  });
}

export async function updateSeasonTemplate(
  id: string,
  data: Partial<NewSeasonTemplate>
): Promise<SeasonTemplate> {
  const db = database();
  const [template] = await db
    .update(schema.seasonTemplates)
    .set({ ...data, updatedAt: new Date() })
    .where(eq(schema.seasonTemplates.id, id))
    .returning();
  return template;
}

export async function setSeasonTemplateActive(
  id: string,
  isActive: boolean
): Promise<SeasonTemplate> {
  return await updateSeasonTemplate(id, { isActive });
}

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