import pool from '../config/db.js';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import crypto from 'crypto';

export class AuthService {
    static async login(email, password) {
        const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email.toLowerCase().trim()]);
        const user = rows[0];

        const dummyHash = '$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345';
        const validPassword = user
            ? await bcrypt.compare(password, user.password_hash)
            : await bcrypt.compare(password, dummyHash);

        if (!user || !validPassword) {
            throw new Error('Invalid credentials');
        }

        const token = jwt.sign(
            { id: user.id, email: user.email, role: user.role },
            process.env.JWT_SECRET,
            { expiresIn: '24h' }
        );

        return { token, user: { id: user.id, email: user.email, name: user.name, role: user.role } };
    }

    static async createUser(data) {
        const { name, email, password, role } = data;
        const password_hash = await bcrypt.hash(password, 10);
        const id = crypto.randomUUID();
        
        await pool.execute(
            'INSERT INTO users (id, name, email, password_hash, role) VALUES (?, ?, ?, ?, ?)',
            [id, name, email.toLowerCase().trim(), password_hash, role]
        );
        
        return { id, name, email, role };
    }
}
