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

export type Team = typeof schema.teams.$inferSelect;
export type NewTeam = typeof schema.teams.$inferInsert;

export async function createTeam(data: NewTeam): Promise<Team> {
  const db = database();
  const [team] = await db.insert(schema.teams).values(data).returning();
  return team;
}

export async function createManyTeams(teams: NewTeam[]): Promise<Team[]> {
  const db = database();
  return await db.insert(schema.teams).values(teams).returning();
}

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

export async function findTeamsBySeasonId(seasonId: string): Promise<Team[]> {
  const db = database();
  return await db.query.teams.findMany({
    where: eq(schema.teams.seasonId, seasonId),
    orderBy: (teams, { asc }) => [asc(teams.name)],
  });
}

export async function findTeamsByOwnerId(ownerId: string): Promise<Team[]> {
  const db = database();
  return await db.query.teams.findMany({
    where: eq(schema.teams.ownerId, ownerId),
    orderBy: (teams, { asc }) => [asc(teams.name)],
  });
}

export async function findTeamByOwnerAndSeason(
  ownerId: string,
  seasonId: string
): Promise<Team | undefined> {
  const db = database();
  return await db.query.teams.findFirst({
    where: and(
      eq(schema.teams.ownerId, ownerId),
      eq(schema.teams.seasonId, seasonId)
    ),
  });
}

export async function findAvailableTeams(seasonId: string): Promise<Team[]> {
  const db = database();
  return await db.query.teams.findMany({
    where: and(
      eq(schema.teams.seasonId, seasonId),
      isNull(schema.teams.ownerId)
    ),
    orderBy: (teams, { asc }) => [asc(teams.name)],
  });
}

export async function updateTeam(
  id: string,
  data: Partial<NewTeam>
): Promise<Team> {
  const db = database();
  const [team] = await db
    .update(schema.teams)
    .set({ ...data, updatedAt: new Date() })
    .where(eq(schema.teams.id, id))
    .returning();
  return team;
}

export async function assignTeamOwner(
  id: string,
  ownerId: string
): Promise<Team> {
  return await updateTeam(id, { ownerId });
}

export async function claimTeam(
  id: string,
  ownerId: string,
  name: string
): Promise<Team> {
  return await updateTeam(id, { ownerId, name });
}

export async function removeTeamOwner(id: string): Promise<Team> {
  return await updateTeam(id, { ownerId: null });
}

export async function renameTeam(id: string, name: string): Promise<Team> {
  return await updateTeam(id, { name });
}

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