import { Hono } from 'hono';
import { randomUUID } from 'crypto';
import { query, withTransaction } from '../db.js';
const FREE_TIER_LIMIT = 10;
const freeTier = new Hono();
// POST /v1/free-charge — consume a free tier file slot
freeTier.post('/free-charge', async (c) => {
    const body = await c.req.json();
    if (!body.machine_id || typeof body.machine_id !== 'string') {
        return c.json({ error: 'machine_id is required' }, 400);
    }
    if (!body.document_hash || typeof body.document_hash !== 'string') {
        return c.json({ error: 'document_hash is required' }, 400);
    }
    const ipAddress = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
    const hostnameHash = body.hostname_hash ?? null;
    const result = withTransaction(() => {
        // Upsert: insert if not exists, update last_seen_at if exists
        query(`INSERT INTO free_machines (machine_id, files_used, ip_address, hostname_hash)
       VALUES (?, 0, ?, ?)
       ON CONFLICT(machine_id) DO UPDATE SET
         last_seen_at = datetime('now'),
         ip_address = excluded.ip_address,
         hostname_hash = COALESCE(excluded.hostname_hash, free_machines.hostname_hash)`, [body.machine_id, ipAddress, hostnameHash]);
        // Check current usage
        const machineResult = query('SELECT files_used FROM free_machines WHERE machine_id = ?', [body.machine_id]);
        if (machineResult.rows.length === 0) {
            throw new Error('Failed to upsert free_machines record');
        }
        const filesUsed = machineResult.rows[0].files_used;
        if (filesUsed >= FREE_TIER_LIMIT) {
            return {
                exhausted: true,
                files_used: filesUsed,
                files_limit: FREE_TIER_LIMIT,
            };
        }
        // Increment usage
        query('UPDATE free_machines SET files_used = files_used + 1 WHERE machine_id = ?', [body.machine_id]);
        const chargeId = `free_${randomUUID()}`;
        const newFilesUsed = filesUsed + 1;
        console.error(`[free-tier] machine=${body.machine_id} charge=${chargeId} files=${newFilesUsed}/${FREE_TIER_LIMIT} ip=${ipAddress}`);
        return {
            exhausted: false,
            charge_id: chargeId,
            files_used: newFilesUsed,
            files_remaining: FREE_TIER_LIMIT - newFilesUsed,
        };
    });
    if (result.exhausted) {
        return c.json({
            error: `Free tier exhausted (${result.files_used}/${result.files_limit} files used). Get a license key at https://ocrprovenance.com/dashboard`,
            files_used: result.files_used,
            files_limit: result.files_limit,
        }, 402);
    }
    return c.json({
        charge_id: result.charge_id,
        files_used: result.files_used,
        files_remaining: result.files_remaining,
    });
});
// GET /v1/free-status — check free tier usage for a machine
freeTier.get('/free-status', async (c) => {
    const machineId = c.req.query('machine_id');
    if (!machineId) {
        return c.json({ error: 'machine_id query parameter is required' }, 400);
    }
    const machineResult = query('SELECT files_used FROM free_machines WHERE machine_id = ?', [machineId]);
    const filesUsed = machineResult.rows.length > 0 ? machineResult.rows[0].files_used : 0;
    return c.json({
        machine_id: machineId,
        files_used: filesUsed,
        files_remaining: FREE_TIER_LIMIT - filesUsed,
        files_limit: FREE_TIER_LIMIT,
    });
});
export default freeTier;
//# sourceMappingURL=free-tier.js.map