import { v4 as uuidv4 } from "uuid";
import { getAdapter } from "../driver.js";

function rowToUser(row) {
  if (!row) return null;
  return {
    id: row.id,
    username: row.username,
    role: row.role,
    is_active: row.is_active === 1 || row.is_active === true,
    is_approved: row.is_approved === 1 || row.is_approved === true,
    created_at: row.created_at,
  };
}

export async function createUser(username, passwordHash) {
  const db = await getAdapter();
  const id = uuidv4();
  const now = new Date().toISOString();
  db.run(
    `INSERT INTO users(id, username, password_hash, role, is_active, is_approved, created_at) VALUES(?, ?, ?, 'user', 1, 0, ?)`,
    [id, username, passwordHash, now]
  );
  return { id, username, role: 'user', is_active: true, is_approved: false, created_at: now };
}

export async function findByUsername(username) {
  const db = await getAdapter();
  const row = db.get(`SELECT * FROM users WHERE username = ?`, [username]);
  return rowToUser(row);
}

export async function findById(id) {
  const db = await getAdapter();
  const row = db.get(`SELECT * FROM users WHERE id = ?`, [id]);
  return rowToUser(row);
}

export async function listUsers() {
  const db = await getAdapter();
  const rows = db.all(`SELECT * FROM users ORDER BY created_at ASC`);
  return rows.map(rowToUser);
}

export async function updateApproval(id, isApproved) {
  const db = await getAdapter();
  db.run(`UPDATE users SET is_approved = ? WHERE id = ?`, [isApproved ? 1 : 0, id]);
}

export async function updateRole(id, role) {
  const db = await getAdapter();
  db.run(`UPDATE users SET role = ? WHERE id = ?`, [role, id]);
}

export async function updateActive(id, isActive) {
  const db = await getAdapter();
  db.run(`UPDATE users SET is_active = ? WHERE id = ?`, [isActive ? 1 : 0, id]);
}

export async function getPasswordHash(username) {
  const db = await getAdapter();
  const row = db.get(`SELECT password_hash FROM users WHERE username = ?`, [username]);
  return row?.password_hash ?? null;
}

export async function deleteUser(id) {
  const db = await getAdapter();
  const res = db.run(`DELETE FROM users WHERE id = ?`, [id]);
  return (res?.changes ?? 0) > 0;
}
