// Task Team — Auth Routes with password + OAuth prep — 2026-03-29
const bcrypt = require('bcryptjs');

async function authRoutes(app) {
    // Register with password
    app.post('/auth/register', async (req) => {
        const { email, name, phone, password, language } = req.body;
        if (!email || !name || !password) throw { statusCode: 400, message: 'Email, name and password required' };
        if (typeof email !== 'string' || !email.includes('@') || email.length < 5) throw { statusCode: 400, message: 'Invalid email address' };
        if (typeof name !== 'string' || name.trim().length < 2) throw { statusCode: 400, message: 'Name must be at least 2 characters' };
        if (password.length < 6) throw { statusCode: 400, message: 'Password must be at least 6 characters' };

        // Check if email exists
        const { rows: existing } = await app.db.query('SELECT id FROM users WHERE email = $1', [email]);
        if (existing.length) throw { statusCode: 409, message: 'Email already registered' };

        const hash = await bcrypt.hash(password, 12);
        const { rows } = await app.db.query(
            'INSERT INTO users (email, name, phone, auth_provider, language, settings) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, email, name, phone, language',
            [email, name, phone, 'email', language || 'cs', JSON.stringify({ password_hash: hash })]
        );
        const token = app.jwt.sign({ id: rows[0].id, email: rows[0].email }, { expiresIn: '7d' });
        return { data: { user: rows[0], token } };
    });

    // Login with password
    app.post('/auth/login', async (req) => {
        const { email, password } = req.body;
        if (!email) throw { statusCode: 400, message: 'Email required' };

        const { rows } = await app.db.query('SELECT id, email, name, phone, language, settings FROM users WHERE email = $1', [email]);
        if (!rows.length) throw { statusCode: 401, message: 'Invalid credentials' };

        const user = rows[0];
        const hash = user.settings?.password_hash;

        // If user has password, verify it
        if (hash && password) {
            const valid = await bcrypt.compare(password, hash);
            if (!valid) throw { statusCode: 401, message: 'Invalid credentials' };
        } else if (hash && !password) {
            throw { statusCode: 400, message: 'Password required' };
        }
        // If no hash (legacy user), allow login without password (backward compat)

        const token = app.jwt.sign({ id: user.id, email: user.email }, { expiresIn: '7d' });
        const { settings, ...safeUser } = user;
        return { data: { user: safeUser, token } };
    });

    // Get current user
    app.get('/auth/me', { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req) => {
        const { rows } = await app.db.query(
            'SELECT id, email, name, phone, language, avatar_url, auth_provider, created_at FROM users WHERE id = $1',
            [req.user.id]
        );
        if (!rows.length) throw { statusCode: 404, message: 'User not found' };
        return { data: rows[0] };
    });

    // Update profile
    app.put('/auth/me', { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req) => {
        const { name, phone, language, avatar_url } = req.body;
        const { rows } = await app.db.query(
            'UPDATE users SET name=COALESCE($1,name), phone=COALESCE($2,phone), language=COALESCE($3,language), avatar_url=COALESCE($4,avatar_url), updated_at=NOW() WHERE id=$5 RETURNING id, email, name, phone, language, avatar_url',
            [name, phone, language, avatar_url, req.user.id]
        );
        return { data: rows[0] };
    });

    // Change password
    app.post('/auth/change-password', { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req) => {
        const { current_password, new_password } = req.body;
        if (!new_password || new_password.length < 6) throw { statusCode: 400, message: 'New password must be at least 6 characters' };

        const { rows } = await app.db.query('SELECT settings FROM users WHERE id = $1', [req.user.id]);
        const hash = rows[0]?.settings?.password_hash;
        if (hash && current_password) {
            const valid = await bcrypt.compare(current_password, hash);
            if (!valid) throw { statusCode: 401, message: 'Current password is incorrect' };
        }

        const newHash = await bcrypt.hash(new_password, 12);
        await app.db.query(
            "UPDATE users SET settings = settings || $1::jsonb, updated_at = NOW() WHERE id = $2",
            [JSON.stringify({ password_hash: newHash }), req.user.id]
        );
        return { status: 'ok', message: 'Password changed' };
    });

    // OAuth routes moved to ./oauth.js (Google, Facebook, Apple)

    // TOTP 2FA setup
    app.post('/auth/2fa/setup', { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req) => {
        // Generate TOTP secret (placeholder - needs speakeasy package)
        return { status: 'not_implemented', message: '2FA coming in next release. Use password auth.' };
    });

    // WebAuthn registration (placeholder)
    app.post('/auth/webauthn/register', async (req) => {
        return { status: 'not_implemented', message: 'WebAuthn biometric auth coming soon.' };
    });

    // Delete account (GDPR + Google Play requirement)
    app.delete("/auth/account", { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req, reply) => {
        const uid = req.user.id;
        await app.db.query("DELETE FROM task_comments WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM subtasks WHERE assigned_to=$1", [uid]);
        await app.db.query("DELETE FROM task_collaboration WHERE from_user_id=$1 OR to_user_id=$1", [uid]);
        await app.db.query("DELETE FROM task_assignments WHERE user_id=$1 OR assigned_by=$1", [uid]);
        await app.db.query("DELETE FROM push_subscriptions WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM goals WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM connectors WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM tasks WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM task_groups WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM users WHERE id=$1", [uid]);
        return reply.send({ data: { deleted: true, message: "Account and all data permanently deleted" } });
    });

    // Alias: /auth/delete-account (backward compat)
    app.delete("/auth/delete-account", { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req, reply) => {
        const uid = req.user.id;
        await app.db.query("DELETE FROM task_comments WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM subtasks WHERE assigned_to=$1", [uid]);
        await app.db.query("DELETE FROM task_collaboration WHERE from_user_id=$1 OR to_user_id=$1", [uid]);
        await app.db.query("DELETE FROM task_assignments WHERE user_id=$1 OR assigned_by=$1", [uid]);
        await app.db.query("DELETE FROM push_subscriptions WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM goals WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM connectors WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM tasks WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM task_groups WHERE user_id=$1", [uid]);
        await app.db.query("DELETE FROM users WHERE id=$1", [uid]);
        return reply.send({ data: { deleted: true, message: "Account and all data permanently deleted" } });
    });

    // OAuth initiate routes moved to ./oauth.js


    // Export all user data (GDPR)
    app.get("/auth/export-data", { preHandler: [async (req) => { await req.jwtVerify(); }] }, async (req) => {
        const userId = req.user.id;
        const { rows: user } = await app.db.query("SELECT id,email,name,phone,language,created_at FROM users WHERE id=$1", [userId]);
        const { rows: tasks } = await app.db.query("SELECT * FROM tasks WHERE user_id=$1", [userId]);
        const { rows: goals } = await app.db.query("SELECT * FROM goals WHERE user_id=$1", [userId]);
        const { rows: groups } = await app.db.query("SELECT * FROM task_groups WHERE user_id=$1 OR user_id IS NULL", [userId]);
        const { rows: comments } = await app.db.query("SELECT * FROM task_comments WHERE user_id=$1", [userId]);
        return {
            exported_at: new Date().toISOString(),
            user: user[0] || {},
            tasks, goals, groups, comments,
            total: { tasks: tasks.length, goals: goals.length, comments: comments.length }
        };
    });

    // Search users by name or email (for collaboration)
    app.get('/auth/users/search', async (req) => {
        const q = (req.query.q || '').trim();
        if (q.length < 2) return { data: [] };
        const { rows } = await app.db.query(
            "SELECT id, name, email, avatar_url FROM users WHERE (name ILIKE $1 OR email ILIKE $1) ORDER BY name LIMIT 20",
            ["%" + q + "%"]
        );
        return { data: rows };
    });

}

module.exports = authRoutes;

