import { eq, and } from "drizzle-orm";
import { drizzle } from "drizzle-orm/mysql2";
import { InsertUser, users, submissions, corrections, grades } 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;
}

// ========== Submissions ==========

export async function createSubmission(submission: typeof submissions.$inferInsert) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  await db.insert(submissions).values(submission);
  return submission;
}

export async function getSubmissionById(id: string) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  const result = await db.select().from(submissions).where(eq(submissions.id, id)).limit(1);
  return result.length > 0 ? result[0] : null;
}

export async function getSubmissionsByClass(series: string, classname: string) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  return db.select().from(submissions)
    .where(and(eq(submissions.series, series), eq(submissions.class, classname)))
    .orderBy(submissions.createdAt);
}

export async function updateSubmissionStatus(id: string, status: "pending" | "correcting" | "completed") {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  await db.update(submissions).set({ status, updatedAt: new Date() }).where(eq(submissions.id, id));
}

// ========== Corrections ==========

export async function createCorrection(correction: typeof corrections.$inferInsert) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  const result = await db.insert(corrections).values(correction);
  return result;
}

export async function getCorrectionBySubmissionId(submissionId: string) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  const result = await db.select().from(corrections)
    .where(eq(corrections.submissionId, submissionId))
    .limit(1);
  return result.length > 0 ? result[0] : null;
}

export async function updateCorrection(id: number, correction: Partial<typeof corrections.$inferInsert>) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  await db.update(corrections).set({ ...correction, updatedAt: new Date() }).where(eq(corrections.id, id));
}

// ========== Grades ==========

export async function createGrade(grade: typeof grades.$inferInsert) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  await db.insert(grades).values(grade);
  return grade;
}

export async function getGradesByClass(classname: string, type?: string) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  if (type) {
    return db.select().from(grades)
      .where(and(eq(grades.class, classname), eq(grades.type, type as any)))
      .orderBy(grades.recordedAt);
  }
  
  return db.select().from(grades)
    .where(eq(grades.class, classname))
    .orderBy(grades.recordedAt);
}

export async function getGradesByStudent(studentName: string) {
  const db = await getDb();
  if (!db) throw new Error("Database not available");
  
  return db.select().from(grades)
    .where(eq(grades.studentName, studentName))
    .orderBy(grades.recordedAt) as any;
}
