import pool from "../config/db";
import bcrypt from "bcryptjs";

export interface User {
  id?: number;
  username: string;
  password: string;
  email: string;
  role?: "operator" | "ia_admin";
  created_at?: Date;
}

export const UserModel = {
  async findByUsername(username: string): Promise<User | null> {
    const [rows] = await pool.query("SELECT * FROM users WHERE username = ?", [username]);
    const arr = rows as User[];
    return arr.length > 0 ? arr[0] : null;
  },

  async findById(id: number): Promise<User | null> {
    const [rows] = await pool.query("SELECT * FROM users WHERE id = ?", [id]);
    const arr = rows as User[];
    return arr.length > 0 ? arr[0] : null;
  },

  async create(username: string, password: string, email: string, role: "operator" | "ia_admin" = "operator"): Promise<User> {
    const hash = await bcrypt.hash(password, 10);
    const [result] = await pool.query(
      "INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, ?)",
      [username, hash, email, role]
    );
    const r = result as any;
    return { id: r.insertId, username, password: hash, email, role };
  },

  async verifyPassword(plainText: string, hash: string): Promise<boolean> {
    return bcrypt.compare(plainText, hash);
  }
};
