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

export type SeasonTemplateSport = typeof schema.seasonTemplateSports.$inferSelect;
export type NewSeasonTemplateSport = typeof schema.seasonTemplateSports.$inferInsert;

export async function addSportToTemplate(
  templateId: string,
  sportsSeasonId: string
): Promise<SeasonTemplateSport> {
  const db = database();
  const [link] = await db
    .insert(schema.seasonTemplateSports)
    .values({
      templateId,
      sportsSeasonId,
    })
    .returning();
  return link;
}

export async function addMultipleSportsToTemplate(
  data: NewSeasonTemplateSport[]
): Promise<SeasonTemplateSport[]> {
  const db = database();
  return await db
    .insert(schema.seasonTemplateSports)
    .values(data)
    .returning();
}

export async function removeSportFromTemplate(
  templateId: string,
  sportsSeasonId: string
): Promise<void> {
  const db = database();
  await db
    .delete(schema.seasonTemplateSports)
    .where(
      and(
        eq(schema.seasonTemplateSports.templateId, templateId),
        eq(schema.seasonTemplateSports.sportsSeasonId, sportsSeasonId)
      )
    );
}

export async function findSeasonTemplateSportsByTemplateId(
  templateId: string
): Promise<SeasonTemplateSport[]> {
  const db = database();
  return await db.query.seasonTemplateSports.findMany({
    where: eq(schema.seasonTemplateSports.templateId, templateId),
    with: {
      sportsSeason: {
        with: {
          sport: true,
        },
      },
    },
  });
}

export async function findSeasonTemplateSportsBySportsSeasonId(
  sportsSeasonId: string
): Promise<SeasonTemplateSport[]> {
  const db = database();
  return await db.query.seasonTemplateSports.findMany({
    where: eq(schema.seasonTemplateSports.sportsSeasonId, sportsSeasonId),
    with: {
      template: true,
    },
  });
}


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