const db = require('../db');

const mockUsers = [
    {
        name: "Ravi Kumar",
        mobile: "9876543210",
        email: "ravi@example.com",
        present_address: { city: "Hyderabad", state: "Telangana", pincode: "500081" },
        role: "customer",
        status: "active"
    },
    {
        name: "Priya Sharma",
        mobile: "9123456780",
        email: "priya@example.com",
        present_address: { city: "Secunderabad", state: "Telangana", pincode: "500003" },
        role: "manager",
        status: "active"
    },
    {
        name: "Arun Varma",
        mobile: "9988776655",
        email: "arun@example.com",
        present_address: { city: "Vijayawada", state: "Andhra Pradesh", pincode: "520001" },
        role: "customer",
        status: "active"
    },
    {
        name: "Anjaneyulu Admin",
        mobile: "9030295951",
        email: "admin@anjaneyulu.in",
        present_address: { city: "Hyderabad", state: "Telangana", pincode: "500081" },
        role: "super_admin",
        status: "active"
    }
];

async function seed() {
    console.log("Seeding mock users...");
    
    // Ensure database sequence and column are setup
    try {
        await db.query(`CREATE SEQUENCE IF NOT EXISTS user_unique_id_seq START WITH 100000;`);
        await db.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS unique_user_id BIGINT UNIQUE DEFAULT nextval('user_unique_id_seq');`);
        console.log("Database schema checked/updated successfully.");
    } catch (err) {
        console.log("Database schema check warning:", err.message);
    }

    for (const u of mockUsers) {
        try {
            // Check if user exists by mobile
            const exists = await db.query("SELECT id FROM users WHERE mobile = $1", [u.mobile]);
            if (exists.rows.length > 0) {
                console.log(`- User with mobile ${u.mobile} already exists, skipping.`);
                continue;
            }

            const res = await db.query(
                `INSERT INTO users (
                    name, mobile, email, present_address, role, status
                ) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, unique_user_id, name`,
                [
                    u.name, u.mobile, u.email, 
                    JSON.stringify(u.present_address), u.role, u.status
                ]
            );
            console.log(`- Seeded User: ${res.rows[0].name} (DB ID: ${res.rows[0].id}, Unique ID: ${res.rows[0].unique_user_id})`);
        } catch (err) {
            console.error(`- Error inserting user ${u.name}:`, err.message);
        }
    }
    console.log("Seeding complete.");
    process.exit();
}

seed();
