import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/mysql2";
import { CashOfferLead, InsertCashOfferLead, InsertUser, cashOfferLeads, users } from "../drizzle/schema";
import { ENV } from './_core/env';

let _db: ReturnType<typeof drizzle> | null = null;

// Lazily create the drizzle instance so local tooling can run without a DB.
export async function getDb() {
  if (!_db && process.env.DATABASE_URL) {
    try {
      _db = drizzle(process.env.DATABASE_URL);
    } catch (error) {
      console.warn("[Database] Failed to connect:", error);
      _db = null;
    }
  }
  return _db;
}

export async function upsertUser(user: InsertUser): Promise<void> {
  if (!user.openId) {
    throw new Error("User openId is required for upsert");
  }

  const db = await getDb();
  if (!db) {
    console.warn("[Database] Cannot upsert user: database not available");
    return;
  }

  try {
    const values: InsertUser = {
      openId: user.openId,
    };
    const updateSet: Record<string, unknown> = {};

    const textFields = ["name", "email", "loginMethod"] as const;
    type TextField = (typeof textFields)[number];

    const assignNullable = (field: TextField) => {
      const value = user[field];
      if (value === undefined) return;
      const normalized = value ?? null;
      values[field] = normalized;
      updateSet[field] = normalized;
    };

    textFields.forEach(assignNullable);

    if (user.lastSignedIn !== undefined) {
      values.lastSignedIn = user.lastSignedIn;
      updateSet.lastSignedIn = user.lastSignedIn;
    }
    if (user.role !== undefined) {
      values.role = user.role;
      updateSet.role = user.role;
    } else if (user.openId === ENV.ownerOpenId) {
      values.role = 'admin';
      updateSet.role = 'admin';
    }

    if (!values.lastSignedIn) {
      values.lastSignedIn = new Date();
    }

    if (Object.keys(updateSet).length === 0) {
      updateSet.lastSignedIn = new Date();
    }

    await db.insert(users).values(values).onDuplicateKeyUpdate({
      set: updateSet,
    });
  } catch (error) {
    console.error("[Database] Failed to upsert user:", error);
    throw error;
  }
}

export async function getUserByOpenId(openId: string) {
  const db = await getDb();
  if (!db) {
    console.warn("[Database] Cannot get user: database not available");
    return undefined;
  }

  const result = await db.select().from(users).where(eq(users.openId, openId)).limit(1);

  return result.length > 0 ? result[0] : undefined;
}

export async function createCashOfferLead(lead: InsertCashOfferLead): Promise<Pick<CashOfferLead, "id">> {
  const db = await getDb();
  if (!db) {
    throw new Error("Lead storage is not available. Please try again shortly.");
  }

  const result = await db.insert(cashOfferLeads).values(lead);
  const insertId = Number(result[0]?.insertId);

  if (!Number.isInteger(insertId) || insertId < 1) {
    throw new Error("Lead storage did not return a valid record identifier.");
  }

  return { id: insertId };
}

export async function updateCashOfferLeadWebhook(
  leadId: number,
  update: Pick<InsertCashOfferLead, "webhookStatus" | "webhookError" | "webhookAttemptedAt">,
): Promise<void> {
  const db = await getDb();
  if (!db) {
    throw new Error("Lead storage is not available for CRM status updates.");
  }

  await db.update(cashOfferLeads).set(update).where(eq(cashOfferLeads.id, leadId));
}
