import { createHmac, randomInt } from "node:crypto";
import { and, eq, isNull, sql } from "drizzle-orm";
import { db } from "@/db";
import { emailVerificationChallenges, userEmails } from "@/db/schema";
import { sendBotEmail } from "@/lib/bot-api";

const PIN_TTL_MS = 10 * 60 * 1000;
const SEND_COOLDOWN_MS = 60 * 1000;
const MAX_SENDS_PER_HOUR = 3;
const MAX_VERIFY_ATTEMPTS = 5;

export class EmailVerificationError extends Error {
  status: number;
  retryAt?: string;
  constructor(message: string, status = 400, retryAt?: string) { super(message); this.status = status; this.retryAt = retryAt; }
}

/** Lowercases and shape-checks the address; optionally strips a technical +tag. */
export function normalizeEmail(input: string, plusMode: "reject" | "strip" = "reject") {
  let email = input.trim().toLowerCase();
  const at = email.lastIndexOf("@");
  const plus = at > 0 ? email.slice(0, at).indexOf("+") : -1;
  if (plus >= 0) {
    if (plusMode === "reject") return null;
    email = `${email.slice(0, plus)}${email.slice(at)}`;
  }
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) && email.length <= 254 ? email : null;
}

function hmac(email: string, pin: string, purpose: string) {
  return createHmac("sha256", process.env.AUTH_SECRET || "kiln-dev-secret").update(`email:${purpose}:${email}:${pin}`).digest("hex");
}

/**
 * Single-use email challenge (§10.2 analogy): 60 s cooldown, at most 3 sends
 * per hour per address, 6-digit PIN stored only as HMAC; the bot is a plain
 * transport (contract §2а).
 */
type EmailPurpose = "client" | "operator" | "admin" | "operator_android";
export async function requestEmailChallenge(params: { email: string; purpose?: EmailPurpose; userId?: number; ip?: string; ttlMs?: number }) {
  if (!db) throw new EmailVerificationError("База данных недоступна", 503);
  const now = new Date(), purpose = params.purpose || "client";
  const pin = String(randomInt(0, 1_000_000)).padStart(6, "0");
  const ttlMs = params.ttlMs || PIN_TTL_MS;
  const challenge = await db.transaction(async tx => {
    await tx.execute(sql`SET LOCAL lock_timeout = '3s'`);
    await tx.execute(sql`SET LOCAL statement_timeout = '5s'`);
    await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${'email:' + purpose + ':' + params.email},0))`);
    const where = and(eq(emailVerificationChallenges.email, params.email), eq(emailVerificationChallenges.purpose, purpose));
    const [recent] = await tx.select().from(emailVerificationChallenges).where(where).orderBy(sql`${emailVerificationChallenges.createdAt} DESC`).limit(1);
    if (recent && now.getTime() - recent.createdAt.getTime() < SEND_COOLDOWN_MS) throw new EmailVerificationError("Повторная отправка пока недоступна.", 429, new Date(recent.createdAt.getTime() + SEND_COOLDOWN_MS).toISOString());
    const [{ count }] = await tx.select({ count: sql<number>`count(*)::int` }).from(emailVerificationChallenges).where(and(where, sql`${emailVerificationChallenges.createdAt} > now() - interval '1 hour'`));
    if (count >= MAX_SENDS_PER_HOUR) throw new EmailVerificationError("Слишком много отправок за час. Попробуйте позже.", 429, new Date(now.getTime() + 3600000).toISOString());
    await tx.update(emailVerificationChallenges).set({ consumedAt: now }).where(and(where, isNull(emailVerificationChallenges.consumedAt)));
    const [created] = await tx.insert(emailVerificationChallenges).values({ email: params.email, purpose, pinHash: hmac(params.email, pin, purpose), userId: params.userId ?? null, ip: params.ip?.slice(0, 64) ?? null, expiresAt: new Date(now.getTime() + ttlMs) }).returning({ id: emailVerificationChallenges.id });
    return created;
  });
  try {
    await sendBotEmail(params.email, "Код подтверждения — ресторан КИЛН", `Ваш код для входа на сайт КИЛН: ${pin}\n\nКод действует ${Math.max(1, Math.ceil(ttlMs / 60000))} минут. Если вы не запрашивали вход, проигнорируйте письмо.`);
  } catch (error) {
    // Never consume a newer challenge if this transport completed late.
    await db.update(emailVerificationChallenges).set({ consumedAt: new Date() }).where(eq(emailVerificationChallenges.id, challenge.id));
    throw new EmailVerificationError((error as { status?: number }).status === 400 ? "Проверьте адрес почты." : "Не удалось отправить письмо. Попробуйте позже.", 502, new Date(now.getTime() + SEND_COOLDOWN_MS).toISOString());
  }
  return { retryAt: new Date(now.getTime() + SEND_COOLDOWN_MS).toISOString() };
}

export async function verifyEmailChallenge(params: { email: string; pin: string; purpose?: EmailPurpose }) {
  if (!db) throw new EmailVerificationError("База данных недоступна", 503);
  const now = new Date(), purpose = params.purpose || "client";
  const failure = await db.transaction(async tx => {
    await tx.execute(sql`SET LOCAL lock_timeout = '3s'`);
    await tx.execute(sql`SET LOCAL statement_timeout = '5s'`);
    await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${'email:' + purpose + ':' + params.email},0))`);
    const [challenge] = await tx.select().from(emailVerificationChallenges).where(and(eq(emailVerificationChallenges.email, params.email), eq(emailVerificationChallenges.purpose, purpose), isNull(emailVerificationChallenges.consumedAt))).orderBy(sql`${emailVerificationChallenges.id} DESC`).limit(1);
    if (!challenge || challenge.expiresAt.getTime() <= Date.now()) return "Код истёк — запросите новый.";
    if (challenge.attempts >= MAX_VERIFY_ATTEMPTS) return "Слишком много попыток — запросите новый код.";
    if (hmac(params.email, params.pin, purpose) !== challenge.pinHash) {
      const attempts = challenge.attempts + 1;
      await tx.update(emailVerificationChallenges).set({ attempts, consumedAt: attempts >= MAX_VERIFY_ATTEMPTS ? now : null }).where(eq(emailVerificationChallenges.id, challenge.id));
      return "Неверный код.";
    }
    await tx.update(emailVerificationChallenges).set({ consumedAt: now }).where(eq(emailVerificationChallenges.id, challenge.id));
    return null;
  });
  if (failure) throw new EmailVerificationError(failure);
}

export async function upsertUserEmail(userId: number, email: string) {
  if (!db) throw new EmailVerificationError("База данных недоступна", 503);
  const now = new Date();
  const [existingByEmail] = await db.select().from(userEmails).where(and(eq(userEmails.email, email), isNull(userEmails.archivedAt))).limit(1);
  if (existingByEmail && existingByEmail.userId !== userId) throw new EmailVerificationError("Не удалось подтвердить почту.");
  const [existingByUser] = await db.select().from(userEmails).where(and(eq(userEmails.userId, userId), isNull(userEmails.archivedAt))).limit(1);
  if (existingByUser) await db.update(userEmails).set({ email, verifiedAt: now, updatedAt: now }).where(eq(userEmails.id, existingByUser.id));
  else await db.insert(userEmails).values({ userId, email, verifiedAt: now });
}

export async function getVerifiedEmail(userId: number) {
  if (!db) return null;
  const [row] = await db.select().from(userEmails).where(and(eq(userEmails.userId, userId), sql`${userEmails.verifiedAt} IS NOT NULL`, isNull(userEmails.archivedAt))).limit(1);
  return row?.email ?? null;
}
