/**
 * Authentication Routes
 * Handles user signup and login
 */

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const { query } = require('../database/connection');
const { ApiError } = require('../middleware/errorHandler');

/**
 * Generate API Key using environment prefix
 */
function generateApiKey() {
    const prefix = process.env.API_KEY_PREFIX || 'vi_';
    return prefix + crypto.randomBytes(24).toString('hex');
}

/**
 * POST /v1/auth/signup
 * Register a new user
 */
router.post('/signup', async (req, res, next) => {
    try {
        const { email, password, name, phone } = req.body;

        if (!email || !password) {
            throw new ApiError(400, 'MISSING_FIELDS', 'Email and password required');
        }

        if (password.length < 8) {
            throw new ApiError(400, 'WEAK_PASSWORD', 'Password must be 8+ characters');
        }

        // Check if email already exists
        const existing = await query('SELECT id FROM users WHERE email = $1', [email.toLowerCase()]);
        if (existing.rows.length > 0) {
            throw new ApiError(409, 'EMAIL_EXISTS', 'Email already registered');
        }

        // Hash password
        const passwordHash = await bcrypt.hash(password, 10);

        // Create user
        const result = await query(
            `INSERT INTO users (email, password_hash, company_name, phone, plan, monthly_quota, quota_reset_date)
       VALUES ($1, $2, $3, $4, 'free', 100, DATE(NOW() + INTERVAL '1 month'))
       RETURNING id, email, company_name, plan`,
            [email.toLowerCase(), passwordHash, name, phone]
        );

        const user = result.rows[0];

        // Generate API key with custom prefix from env
        const apiKey = generateApiKey();
        const keyHash = crypto.createHash('sha256').update(apiKey).digest('hex');
        const keyPrefix = process.env.API_KEY_PREFIX || 'vi_';

        // Store API key
        await query(
            `INSERT INTO api_keys (user_id, key_prefix, key_hash, key_hint, name)
       VALUES ($1, $2, $3, $4, 'Default')`,
            [user.id, keyPrefix, keyHash, apiKey.slice(-4)]
        );

        // Generate JWT token
        const token = jwt.sign(
            { userId: user.id, email: user.email },
            process.env.JWT_SECRET,
            { expiresIn: '7d' }
        );

        res.status(201).json({
            success: true,
            data: {
                user: {
                    id: user.id,
                    email: user.email,
                    name: user.company_name,
                    plan: user.plan
                },
                api_key: apiKey,
                token
            }
        });

    } catch (error) {
        next(error);
    }
});

/**
 * POST /v1/auth/login
 * Authenticate existing user
 */
router.post('/login', async (req, res, next) => {
    try {
        const { email, password } = req.body;

        if (!email || !password) {
            throw new ApiError(400, 'MISSING_FIELDS', 'Email and password required');
        }

        // Find user
        const result = await query(
            'SELECT * FROM users WHERE email = $1 AND is_active = true',
            [email.toLowerCase()]
        );

        if (result.rows.length === 0) {
            throw new ApiError(401, 'INVALID_CREDENTIALS', 'Invalid email or password');
        }

        const user = result.rows[0];

        // Verify password
        const validPassword = await bcrypt.compare(password, user.password_hash);

        if (!validPassword) {
            throw new ApiError(401, 'INVALID_CREDENTIALS', 'Invalid email or password');
        }

        // Update last login
        await query('UPDATE users SET last_login_at = NOW() WHERE id = $1', [user.id]);

        // Generate JWT token
        const token = jwt.sign(
            { userId: user.id, email: user.email },
            process.env.JWT_SECRET,
            { expiresIn: '7d' }
        );

        res.json({
            success: true,
            data: {
                user: {
                    id: user.id,
                    email: user.email,
                    name: user.company_name,
                    plan: user.plan,
                    quota: user.monthly_quota,
                    used: user.calls_this_month
                },
                token
            }
        });

    } catch (error) {
        next(error);
    }
});

module.exports = router;
