import type { ResultSetHeader, RowDataPacket } from "mysql2/promise";
import { pool } from "../db/mysql.js";
import { hashPassword } from "../crypto/password.js";

/** Usuários do painel (`panel_users`). */

export type Role = "admin" | "operator";

export interface PanelUserRow {
  id: number;
  name: string;
  email: string;
  password_hash: string;
  role: Role;
  active: number;
}

type Row = PanelUserRow & RowDataPacket;

export async function findByEmail(email: string): Promise<PanelUserRow | null> {
  const [rows] = await pool.query<Row[]>(
    `SELECT id, name, email, password_hash, role, active
       FROM panel_users WHERE email = :email`,
    { email },
  );
  return rows[0] ?? null;
}

export async function findById(id: number): Promise<PanelUserRow | null> {
  const [rows] = await pool.query<Row[]>(
    `SELECT id, name, email, password_hash, role, active
       FROM panel_users WHERE id = :id`,
    { id },
  );
  return rows[0] ?? null;
}

export interface CreateUserInput {
  name: string;
  email: string;
  password: string;
  role?: Role;
}

export async function createUser(input: CreateUserInput): Promise<number> {
  const passwordHash = await hashPassword(input.password);
  const [res] = await pool.query<ResultSetHeader>(
    `INSERT INTO panel_users (name, email, password_hash, role)
     VALUES (:name, :email, :passwordHash, :role)`,
    {
      name: input.name,
      email: input.email,
      passwordHash,
      role: input.role ?? "operator",
    },
  );
  return res.insertId;
}
