// apps/api/src/controllers/auth.controller.js

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { validationResult } = require('express-validator');
const { DatabaseClient } = require('../../../../packages/db/client');

const db = new DatabaseClient();

exports.register = async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { email, password, full_name, company, phone } = req.body;
        
        // Check if user exists
        const existingUser = await db.get('SELECT id FROM users WHERE email = ?', [email]);
        if (existingUser) {
            return res.status(400).json({ error: 'User already exists' });
        }
        
        // Hash password
        const hashedPassword = await bcrypt.hash(password, 10);
        
        // Create user with plan='free'
        const result = await db.run(
            'INSERT INTO users (email, password_hash, full_name, company, phone, role, plan, daily_credits) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
            [email, hashedPassword, full_name, company, phone, 'user', 'free', 5]
        );
        
        // Generate token
        const token = jwt.sign(
            { id: result.insertId, email, role: 'user' },
            process.env.JWT_SECRET,
            { expiresIn: process.env.JWT_EXPIRE || '7d' }
        );
        
        res.status(201).json({
            message: 'User registered successfully',
            token,
            user: { id: result.insertId, email, full_name, role: 'user', plan: 'free' }
        });
    } catch (error) {
        console.error('Registration error:', error);
        res.status(500).json({ error: 'Registration failed' });
    }
};

exports.login = async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { email, password } = req.body;
        
        // Get user
        const user = await db.get('SELECT * FROM users WHERE email = ? AND is_active = true', [email]);
        if (!user) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        
        // Verify password
        const isValid = await bcrypt.compare(password, user.password_hash);
        if (!isValid) {
            return res.status(401).json({ error: 'Invalid credentials' });
        }
        
        // Update last login
        await db.run('UPDATE users SET last_login = datetime("now") WHERE id = ?', [user.id]);
        
        // Generate token
        const token = jwt.sign(
            { id: user.id, email: user.email, role: user.role },
            process.env.JWT_SECRET,
            { expiresIn: process.env.JWT_EXPIRE || '7d' }
        );
        
        res.json({
            message: 'Login successful',
            token,
            user: {
                id: user.id,
                email: user.email,
                full_name: user.full_name,
                role: user.role,
                plan: user.plan || 'free',
                credits: user.credits
            }
        });
    } catch (error) {
        console.error('Login error:', error);
        res.status(500).json({ error: 'Login failed' });
    }
};

exports.logout = async (req, res) => {
    res.json({ message: 'Logged out successfully' });
};

exports.getCurrentUser = async (req, res) => {
    try {
        // Check if req.user exists (set by auth middleware)
        if (!req.user || !req.user.id) {
            return res.status(401).json({ error: 'Not authenticated' });
        }
        
        const user = await db.get(
            'SELECT id, email, full_name, company, phone, role, plan, credits, searches_count, leads_viewed, bookmarks_count, created_at FROM users WHERE id = ?',
            [req.user.id]
        );
        
        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }
        
        res.json(user);
    } catch (error) {
        console.error('Get user error:', error);
        res.status(500).json({ error: 'Failed to get user' });
    }
};

exports.updateProfile = async (req, res) => {
    try {
        const { full_name, company, phone } = req.body;
        
        await db.run(
            'UPDATE users SET full_name = ?, company = ?, phone = ? WHERE id = ?',
            [full_name, company, phone, req.user.id]
        );
        
        res.json({ message: 'Profile updated successfully' });
    } catch (error) {
        console.error('Update profile error:', error);
        res.status(500).json({ error: 'Failed to update profile' });
    }
};