import { pool } from "./config/db.js";
import crypto from "crypto";

function hashPassword(password) {
  return crypto.createHash("sha256").update(password).digest("hex");
}

async function seed() {
  console.log("Seeding default users...");
  try {
    const defaultUsers = [
      { 
        username: "admin", 
        password: hashPassword("admin123"), 
        role: "admin",
        full_name: "Administrador del Sistema",
        email: "admin@laundryexpress.com",
        phone: "(809) 555-0100",
        status: "active"
      },
      { 
        username: "user", 
        password: hashPassword("user123"), 
        role: "user",
        full_name: "Operador de Lavandería",
        email: "operator@laundryexpress.com",
        phone: "(809) 555-0101",
        status: "active"
      }
    ];

    for (const u of defaultUsers) {
      // Check if user exists
      const [existing] = await pool.query("SELECT id FROM users WHERE username = ?", [u.username]);
      if (existing.length === 0) {
        await pool.query(
          "INSERT INTO users (username, password, role, full_name, email, phone, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())",
          [u.username, u.password, u.role, u.full_name, u.email, u.phone, u.status]
        );
        console.log(`User '${u.username}' created successfully.`);
      } else {
        // Update existing user with fields
        await pool.query(
          "UPDATE users SET role = ?, full_name = ?, email = ?, phone = ?, status = ?, updated_at = NOW() WHERE username = ?",
          [u.role, u.full_name, u.email, u.phone, u.status, u.username]
        );
        console.log(`User '${u.username}' already exists. Updated details.`);
      }
    }

    console.log("Seeding users complete!");
    process.exit(0);
  } catch (err) {
    console.error("Seeding users failed:", err);
    process.exit(1);
  }
}

seed();
