import { authMiddleware } from '../auth/middleware.js';
import { supabase } from '../utils/supabase.js';
import { getPendingApprovals, decideApproval, getApprovalRequest, handleApprovalResponse, } from './manager.js';
/**
 * Resolve req.tenant from req.user before approval routes run. The original
 * version of these routes assumed tenantMiddleware ran first — but the
 * tenantMiddleware in auth/middleware.ts requires a tenantId in the URL
 * params, which approval routes don't have. Without this preHandler,
 * `req.tenant?.id` was always undefined and ownership checks silently
 * passed (security audit HIGH-4).
 */
async function resolveTenantPreHandler(req, _reply) {
    if (req.tenant?.id)
        return;
    if (!req.user?.id)
        return;
    const { data } = await supabase
        .from('tenants')
        .select('*')
        .eq('owner_id', req.user.id)
        .order('created_at', { ascending: false })
        .limit(1);
    const row = data?.[0];
    if (row) {
        req.tenant = row;
    }
}
export async function registerApprovalRoutes(app) {
    // GET /api/approvals/pending — List pending approvals
    app.get('/api/approvals/pending', {
        preHandler: [authMiddleware, resolveTenantPreHandler],
    }, async (req, reply) => {
        const tenantId = req.tenant?.id;
        if (!tenantId) {
            return reply.status(401).send({ error: 'Unauthorized — no tenant for this user' });
        }
        const approvals = await getPendingApprovals(tenantId);
        reply.send({ approvals });
    });
    // GET /api/approvals/:id — Get approval request details
    app.get('/api/approvals/:id', {
        preHandler: [authMiddleware, resolveTenantPreHandler],
    }, async (req, reply) => {
        const { id } = req.params;
        const tenantId = req.tenant?.id;
        if (!tenantId) {
            return reply.status(401).send({ error: 'Unauthorized — no tenant for this user' });
        }
        const approvalReq = await getApprovalRequest(id);
        if (!approvalReq || approvalReq.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Approval request not found' });
        }
        reply.send({ request: approvalReq });
    });
    // POST /api/approvals/:id/decide — Approve or deny
    app.post('/api/approvals/:id/decide', {
        preHandler: [authMiddleware, resolveTenantPreHandler],
    }, async (req, reply) => {
        const { id } = req.params;
        const { approved, reason } = req.body;
        const tenantId = req.tenant?.id;
        const approvalReq = await getApprovalRequest(id);
        if (!approvalReq || approvalReq.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Approval request not found' });
        }
        const decision = {
            approved,
            reason,
        };
        const result = await decideApproval(id, decision, tenantId);
        reply.send({ success: true, request: result });
    });
    // POST /api/approvals/:id/respond — Quick respond with emoji/text
    app.post('/api/approvals/:id/respond', {
        preHandler: [authMiddleware, resolveTenantPreHandler],
    }, async (req, reply) => {
        const { id } = req.params;
        const { response } = req.body;
        const tenantId = req.tenant?.id;
        const approvalReq = await getApprovalRequest(id);
        if (!approvalReq || approvalReq.tenant_id !== tenantId) {
            return reply.status(404).send({ error: 'Approval request not found' });
        }
        const result = await handleApprovalResponse(id, response, tenantId);
        if (!result.success) {
            return reply.status(400).send({ error: result.message });
        }
        reply.send(result);
    });
}
//# sourceMappingURL=routes.js.map