// Task Team — WebAuthn Biometric Auth
// Note: Full WebAuthn needs @simplewebauthn/server, but we create the API structure
async function webauthnFeature(app) {
    await app.db.query(`
        CREATE TABLE IF NOT EXISTS webauthn_credentials (
            id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
            user_id UUID REFERENCES users(id) ON DELETE CASCADE,
            credential_id TEXT UNIQUE NOT NULL,
            public_key TEXT NOT NULL,
            counter INTEGER DEFAULT 0,
            device_name VARCHAR(100),
            created_at TIMESTAMPTZ DEFAULT NOW()
        )
    `).catch(() => {});

    // Registration options
    app.post('/webauthn/register/options', async (req) => {
        const { user_id } = req.body;
        const { rows } = await app.db.query('SELECT id,email,name FROM users WHERE id=$1', [user_id]);
        if (!rows.length) throw { statusCode: 404, message: 'User not found' };
        return { data: {
            challenge: require('crypto').randomBytes(32).toString('base64url'),
            rp: { name: 'Task Team', id: 'tasks.hasdo.info' },
            user: { id: Buffer.from(rows[0].id).toString('base64url'), name: rows[0].email, displayName: rows[0].name },
            pubKeyCredParams: [{ alg: -7, type: 'public-key' }, { alg: -257, type: 'public-key' }],
            authenticatorSelection: { authenticatorAttachment: 'platform', userVerification: 'required' },
            timeout: 60000
        }};
    });

    // Save registration
    app.post('/webauthn/register/verify', async (req) => {
        const { user_id, credential_id, public_key, device_name } = req.body;
        const { rows } = await app.db.query(
            'INSERT INTO webauthn_credentials (user_id, credential_id, public_key, device_name) VALUES ($1,$2,$3,$4) RETURNING *',
            [user_id, credential_id, public_key, device_name || 'Biometric']);
        return { data: rows[0], status: 'registered' };
    });

    // Auth options
    app.post('/webauthn/auth/options', async (req) => {
        const { user_id } = req.body;
        const { rows } = await app.db.query('SELECT credential_id FROM webauthn_credentials WHERE user_id=$1', [user_id]);
        return { data: {
            challenge: require('crypto').randomBytes(32).toString('base64url'),
            allowCredentials: rows.map(r => ({ id: r.credential_id, type: 'public-key' })),
            timeout: 60000, userVerification: 'required'
        }};
    });

    // List user's biometric devices
    app.get('/webauthn/devices/:userId', async (req) => {
        const { rows } = await app.db.query(
            'SELECT id, device_name, created_at FROM webauthn_credentials WHERE user_id=$1', [req.params.userId]);
        return { data: rows };
    });

    // Remove device
    app.delete('/webauthn/devices/:id', async (req) => {
        await app.db.query('DELETE FROM webauthn_credentials WHERE id=$1', [req.params.id]);
        return { status: 'deleted' };
    });
}
module.exports = webauthnFeature;
