import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
import { env } from "../../config/env.js";

type Field = { type: string; name: string; length: number; string(): string | null };
const ID = /(^|_)id$|Id$|^id$|_by$|By$/;
/** Ids are strings, numbers are numbers, dates are "YYYY-MM-DD" and timestamps are ISO UTC. Never Date objects. */
export function typeCast(field: Field, next: () => unknown): unknown {
  switch (field.type) {
    case "LONGLONG": { const s = field.string(); return s === null ? null : ID.test(field.name) ? s : Number(s); }
    case "NEWDECIMAL": case "DECIMAL": { const s = field.string(); return s === null ? null : Number(s); }
    case "DATE": case "NEWDATE": return field.string();
    case "DATETIME": case "TIMESTAMP": { const s = field.string(); return s === null ? null : `${s.replace(" ", "T").slice(0, 23)}Z`; }
    case "TINY": { const s = field.string(); return s === null ? null : Number(s); }
    default: return next();
  }
}
export const poolOptions = (uri: string): mysql.PoolOptions => ({
  // MySQL 8 sends its password key over the connection. That is safe only when the database is on this computer.
  allowPublicKeyRetrieval: ["127.0.0.1", "localhost", "[::1]"].includes(new URL(uri).hostname),
  uri, connectionLimit: 20, charset: "utf8mb4_unicode_ci", timezone: "Z", dateStrings: true, typeCast: typeCast as unknown as NonNullable<mysql.PoolOptions["typeCast"]>,
});
export const pool: Pool = mysql.createPool(poolOptions(env.DATABASE_URL));
// A shared server may run in local time with lenient rules. V2 always works in UTC and refuses bad values.
pool.on("connection", (c) => { void c.query("SET time_zone='+00:00', sql_mode='STRICT_ALL_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO'"); });

/** A pool, or the connection of the running transaction. */
export type Db = Pool | PoolConnection;
export type SqlValue = string | number | bigint | boolean | null | Date | Buffer | readonly (string | number | null | readonly (string | number | null)[])[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Row = Record<string, any>;

export async function query<T = Row>(db: Db, sql: string, params: SqlValue[] = []): Promise<T[]> {
  const [rows] = await db.query<RowDataPacket[]>(sql, params);
  return rows as T[];
}
export const one = async <T = Row>(db: Db, sql: string, params: SqlValue[] = []): Promise<T | undefined> => (await query<T>(db, sql, params))[0];
export async function execute(db: Db, sql: string, params: SqlValue[] = []): Promise<ResultSetHeader> {
  const [result] = await db.query<ResultSetHeader>(sql, params);
  return result;
}
export async function insert(db: Db, table: string, row: Record<string, SqlValue | undefined>): Promise<string> {
  const keys = Object.keys(row).filter((k) => row[k] !== undefined);
  const r = await execute(db, `INSERT INTO ${table} (${keys.join(",")}) VALUES (${keys.map(() => "?").join(",")})`, keys.map((k) => row[k] as SqlValue));
  return String(r.insertId);
}
export async function update(db: Db, table: string, id: string, row: Record<string, SqlValue | undefined>): Promise<number> {
  const keys = Object.keys(row).filter((k) => row[k] !== undefined);
  if (!keys.length) return 0;
  return (await execute(db, `UPDATE ${table} SET ${keys.map((k) => `${k}=?`).join(",")} WHERE id=?`, [...keys.map((k) => row[k] as SqlValue), id])).affectedRows;
}
/** Multi-row insert in chunks. `tail` can hold ON DUPLICATE KEY UPDATE. */
export async function insertMany(db: Db, table: string, columns: string[], rows: (string | number | null)[][], tail = ""): Promise<void> {
  // At most 500 rows and about 400 KB per statement: a default server accepts 1 MB.
  for (let i = 0; i < rows.length;) {
    let n = 0, size = 0;
    while (i + n < rows.length && n < 500 && (n === 0 || size < 400_000)) size += JSON.stringify(rows[i + n++]).length;
    await db.query(`INSERT INTO ${table} (${columns.join(",")}) VALUES ? ${tail}`, [rows.slice(i, i + n)]);
    i += n;
  }
}
export async function transaction<T>(work: (tx: PoolConnection) => Promise<T>, from: Pool = pool): Promise<T> {
  const tx = await from.getConnection();
  try {
    await tx.beginTransaction();
    const result = await work(tx);
    await tx.commit();
    return result;
  } catch (error) {
    await tx.rollback();
    throw error;
  } finally {
    tx.release();
  }
}
export const json = <T>(v: unknown, fallback: T): T => (typeof v === "string" ? (JSON.parse(v) as T) : v === null || v === undefined ? fallback : (v as T));
