const mysql = require("mysql2/promise");

let pool = null;

function isMysqlConfigured() {
  return Boolean(process.env.MYSQL_HOST && String(process.env.MYSQL_HOST).trim());
}

function getMysqlPool() {
  if (!isMysqlConfigured()) {
    return null;
  }
  if (!pool) {
    pool = mysql.createPool({
      host: process.env.MYSQL_HOST.trim(),
      port: Number(process.env.MYSQL_PORT || 3306),
      user: process.env.MYSQL_USER || "root",
      password: process.env.MYSQL_PASSWORD || "",
      database: process.env.MYSQL_DATABASE || "Resume",
      waitForConnections: true,
      connectionLimit: Number(process.env.MYSQL_POOL_SIZE || 10),
      queueLimit: 0,
      enableKeepAlive: true,
      connectTimeout: Number(process.env.MYSQL_CONNECT_TIMEOUT_MS || 15000),
    });
  }
  return pool;
}

async function testMysqlConnection() {
  if (!isMysqlConfigured()) {
    return { ok: false, skipped: true, message: "未配置 MYSQL_HOST" };
  }
  const p = getMysqlPool();
  const conn = await p.getConnection();
  try {
    await conn.query("SELECT 1 AS ok");
    const [rows] = await conn.query("SELECT DATABASE() AS db");
    return {
      ok: true,
      skipped: false,
      database: rows[0]?.db || null,
    };
  } finally {
    conn.release();
  }
}

async function getMysqlHealth() {
  try {
    const r = await testMysqlConnection();
    if (r.skipped) {
      return { ok: false, skipped: true };
    }
    return { ok: true, skipped: false, database: r.database };
  } catch (err) {
    return {
      ok: false,
      skipped: false,
      error: err?.message || String(err),
    };
  }
}

const CREATE_RESUME_SUBMISSIONS_SQL = `
CREATE TABLE IF NOT EXISTS resume_submissions (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  original_filename VARCHAR(512) NOT NULL,
  mime_type VARCHAR(255) NOT NULL,
  source_type VARCHAR(32) NOT NULL,
  file_sha256 CHAR(64) NOT NULL,
  name VARCHAR(255) NULL COMMENT '姓名',
  city VARCHAR(255) NULL COMMENT '城市',
  age VARCHAR(64) NULL COMMENT '年龄',
  expected_salary VARCHAR(255) NULL COMMENT '期望薪资',
  education_experience TEXT NULL COMMENT '教育经历',
  education VARCHAR(512) NULL COMMENT '学历',
  ability TEXT NULL COMMENT '能力',
  work_experience TEXT NULL COMMENT '工作经历',
  project_experience TEXT NULL COMMENT '项目经历',
  tech_stack TEXT NULL COMMENT '技术栈',
  interview_report JSON NULL COMMENT 'AI面试题与评估',
  pdf_meta JSON NULL COMMENT 'PDF解析元信息',
  parser VARCHAR(64) NULL,
  parser_note TEXT NULL,
  warnings_json JSON NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_file_sha256 (file_sha256),
  KEY idx_name (name(64)),
  KEY idx_city (city(64)),
  KEY idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`;

async function ensureResumeTables() {
  const pool = getMysqlPool();
  if (!pool) {
    return { ok: false, skipped: true };
  }
  const conn = await pool.getConnection();
  try {
    const [legacy] = await conn.query(
      `SELECT COUNT(*) AS n FROM INFORMATION_SCHEMA.COLUMNS
       WHERE TABLE_SCHEMA = DATABASE()
         AND TABLE_NAME = 'resume_submissions'
         AND COLUMN_NAME = 'extracted_text'`
    );
    if (legacy[0]?.n > 0) {
      await conn.query("DROP TABLE IF EXISTS resume_submissions");
      console.log("[mysql] 已删除旧版 resume_submissions（含 extracted_text），将按字段重建");
    }
    await conn.query(CREATE_RESUME_SUBMISSIONS_SQL);
    return { ok: true };
  } finally {
    conn.release();
  }
}

function dbRowToParsed(row) {
  if (!row) {
    return null;
  }
  return {
    姓名: row.name || "",
    城市: row.city || "",
    年龄: row.age || "",
    期望薪资: row.expected_salary || "",
    教育经历: row.education_experience || "",
    学历: row.education || "",
    能力: row.ability || "",
    工作经历: row.work_experience || "",
    项目经历: row.project_experience || "",
    技术栈: row.tech_stack || "",
  };
}

async function findDuplicateResumeByFileHash(fileSha256) {
  const pool = getMysqlPool();
  if (!pool || !fileSha256) {
    return null;
  }
  const [rows] = await pool.execute(
    `SELECT * FROM resume_submissions
     WHERE file_sha256 = ?
       AND interview_report IS NOT NULL
     ORDER BY id DESC
     LIMIT 1`,
    [fileSha256]
  );
  return rows[0] || null;
}

async function insertResumeSubmission(row) {
  const pool = getMysqlPool();
  if (!pool) {
    return null;
  }
  const sql = `
    INSERT INTO resume_submissions (
      original_filename,
      mime_type,
      source_type,
      file_sha256,
      name,
      city,
      age,
      expected_salary,
      education_experience,
      education,
      ability,
      work_experience,
      project_experience,
      tech_stack,
      interview_report,
      pdf_meta,
      parser,
      parser_note,
      warnings_json
    ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
  `;
  const params = [
    row.originalFilename,
    row.mimeType,
    row.sourceType,
    row.fileSha256,
    row.name ?? null,
    row.city ?? null,
    row.age ?? null,
    row.expectedSalary ?? null,
    row.educationExperience ?? null,
    row.education ?? null,
    row.ability ?? null,
    row.workExperience ?? null,
    row.projectExperience ?? null,
    row.techStack ?? null,
    row.interviewReport ?? null,
    row.pdfMeta ?? null,
    row.parser ?? null,
    row.parserNote ?? null,
    row.warningsJson ?? null,
  ];
  const [result] = await pool.execute(sql, params);
  return result.insertId;
}

module.exports = {
  getMysqlPool,
  testMysqlConnection,
  getMysqlHealth,
  isMysqlConfigured,
  ensureResumeTables,
  insertResumeSubmission,
  findDuplicateResumeByFileHash,
  dbRowToParsed,
};
