import { eq } from "drizzle-orm";
import * as schema from "~/database/schema";
import type { database } from "~/database/context";
import { findDiscordIdsByUserIds } from "~/models/account";
import { sendPickAnnouncementNotification } from "~/services/discord";
import { logger } from "~/lib/logger";

export async function notifyPickMadeOnDiscord(params: {
  seasonId: string;
  pickedTeamName: string;
  participantName: string;
  sportName: string;
  pickNumber: number;
  round: number;
  pickInRound: number;
  isDraftComplete: boolean;
  nextDraftSlotTeamId: string | null;
  db: ReturnType<typeof database>;
}): Promise<void> {
  const {
    seasonId,
    pickedTeamName,
    participantName,
    sportName,
    pickNumber,
    round,
    pickInRound,
    isDraftComplete,
    nextDraftSlotTeamId,
    db,
  } = params;

  try {
    const season = await db.query.seasons.findFirst({
      where: eq(schema.seasons.id, seasonId),
    });
    if (!season) return;

    const league = await db.query.leagues.findFirst({
      where: eq(schema.leagues.id, season.leagueId),
    });
    if (!league?.discordWebhookUrl || !league.discordPicksAnnouncementEnabled) return;

    const appUrl = process.env.APP_URL ?? "https://brackt.com";
    const draftUrl = `${appUrl}/leagues/${season.leagueId}/draft/${seasonId}`;

    let nextTeamName: string | undefined;
    let nextOwnerDiscordId: string | undefined;

    if (!isDraftComplete && nextDraftSlotTeamId) {
      const nextTeam = await db.query.teams.findFirst({
        where: eq(schema.teams.id, nextDraftSlotTeamId),
      });
      if (nextTeam) {
        nextTeamName = nextTeam.name;
        if (nextTeam.ownerId) {
          const owner = await db.query.users.findFirst({
            where: eq(schema.users.id, nextTeam.ownerId),
          });
          if (owner?.discordPingEnabled) {
            const discordIds = await findDiscordIdsByUserIds([owner.id]);
            nextOwnerDiscordId = discordIds.get(owner.id);
          }
        }
      }
    }

    await sendPickAnnouncementNotification({
      webhookUrl: league.discordWebhookUrl,
      draftUrl,
      pickNumber,
      round,
      pickInRound,
      pickedTeamName,
      participantName,
      sportName,
      nextTeamName,
      nextOwnerDiscordId,
      isDraftComplete,
    });
  } catch (err) {
    logger.error("[DiscordPick] Failed to send pick announcement:", err);
  }
}
