/*
|--------------------------------------------------------------------------
| Agência PSI — Edge Function: asaas-cancel-payment
|--------------------------------------------------------------------------
| Cancela cobrança Asaas. Atualização do financial_record fica pro webhook
| (PAYMENT_DELETED) — single source of truth.
|
| ⚠️ STUB — chamada real ao Asaas marcada TODO.
|
| Input: { tenant_id, asaas_payment_id }
| Output: { ok: true } ou { ok: false, error }
|--------------------------------------------------------------------------
*/
import { adminClient, tenantDbForId } from '../_shared/tenant.ts';

const corsHeaders = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
    'Access-Control-Allow-Methods': 'POST, OPTIONS'
};

function json(body: unknown, status = 200) {
    return new Response(JSON.stringify(body), {
        status,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
}

Deno.serve(async (req: Request) => {
    if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
    if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405);

    try {
        const body = (await req.json().catch(() => null)) as Record<string, unknown> | null;
        if (!body) return json({ ok: false, error: 'invalid_body' }, 400);

        const tenantId = String(body.tenant_id || '');
        const asaasPaymentId = String(body.asaas_payment_id || '');

        if (!tenantId || !asaasPaymentId) return json({ ok: false, error: 'missing_fields' }, 400);

        const admin = adminClient();
        const tdb = await tenantDbForId(admin, tenantId);

        // 1. Lê config + API key
        const { data: settings } = await tdb.from('payment_settings').select('asaas_enabled, asaas_environment, asaas_api_key_sandbox, asaas_api_key_prod').maybeSingle();

        if (!settings?.asaas_enabled) return json({ ok: false, error: 'gateway_not_enabled' }, 403);

        const environment = settings.asaas_environment || 'sandbox';
        const apiKey = environment === 'prod' ? settings.asaas_api_key_prod : settings.asaas_api_key_sandbox;
        const apiUrl = environment === 'prod'
            ? Deno.env.get('ASAAS_API_URL_PROD') || 'https://api.asaas.com/v3'
            : Deno.env.get('ASAAS_API_URL_SANDBOX') || 'https://sandbox.asaas.com/api/v3';

        if (!apiKey) return json({ ok: false, error: 'api_key_missing' }, 403);

        // 2. Verifica que payment pertence ao tenant
        const { data: payment } = await tdb.from('asaas_payments').select('id, status, cancelled_at').eq('asaas_payment_id', asaasPaymentId).eq('environment', environment).maybeSingle();

        if (!payment) return json({ ok: false, error: 'payment_not_found' }, 404);
        if (payment.cancelled_at) return json({ ok: true, already_cancelled: true });

        // 3. DELETE /payments/:id no Asaas
        // TODO Fase B:
        // const resp = await fetch(`${apiUrl}/payments/${asaasPaymentId}`, {
        //     method: 'DELETE',
        //     headers: { 'access_token': apiKey }
        // });
        // const asaasResult = await resp.json();
        // if (!resp.ok) throw new Error(asaasResult.errors?.[0]?.description || 'asaas_delete_failed');

        // 4. UPDATE asaas_payments.cancelled_at
        // (webhook PAYMENT_DELETED também vai chegar, mas update aqui é mais rápido pra UI)

        return json({
            ok: false,
            error: 'STUB_not_implemented_TODO_fase_B',
            note: 'Edge Function estruturada — implementar DELETE call quando Asaas configurado.',
            api_url: apiUrl,
            environment
        }, 501);
    } catch (err) {
        console.error('[asaas-cancel-payment] fatal:', err);
        return json({ ok: false, error: String(err) }, 500);
    }
});
