describe('Financeiro → Bancos: Aba Asaas e dropdowns', () => {
  it('Remove campo redundante e salva config Asaas', () => {
    cy.intercept('GET', '/api/financeiro/bancos/contas*', {
      statusCode: 200,
      body: { data: [
        { id: 1, banco: 'Itaú', agencia: '0001', conta: '12345-6', status: 'ativa' },
        { id: 2, banco: 'Caixa', agencia: '0002', conta: '65432-1', status: 'inativa' }
      ] }
    }).as('getContas');
    cy.intercept('GET', '/api/addons/asaas/config', { statusCode: 200, body: { ok: true, config: { environment: 'production', has_api_key: false } } }).as('getAsaasCfg');
    cy.visit('/financeiro/bancos?tab=asaas');
    cy.wait('@getContas');
    cy.wait('@getAsaasCfg');
    cy.contains('h2', 'Asaas — Credenciais').should('be.visible');
    cy.contains('label', 'Webhook Secret (opcional)').should('not.exist');
    cy.get('#asaasEnv').select('sandbox');
    cy.get('#asaasBaseUrl').clear().type('https://sandbox.asaas.com/api/v3');
    cy.get('#asaasApiKey').type('sk_test_asaas');
    cy.intercept('POST', '/api/addons/asaas/config', { statusCode: 200, body: { ok: true } }).as('postAsaasCfg');
    cy.get('#btnSaveAsaasCfg').click();
    cy.wait('@postAsaasCfg');
    cy.get('#asaasSaveMsg').should('contain.text', 'Configuração salva');
  });

  it('Lista clientes e gera link de pagamento Asaas', () => {
    cy.intercept('GET', '/api/addons/asaas/customers*', { statusCode: 200, body: { data: [{ id: 'cus_1', name: 'Cliente Teste' }] } }).as('getCustomers');
    cy.intercept('GET', '/api/addons/asaas/payments', { statusCode: 200, body: { data: [{ id: 'pay_1', status: 'CONFIRMED' }] } }).as('getPayments');
    cy.intercept('POST', '/api/addons/asaas/payment-links', { statusCode: 200, body: { data: { link_url: 'https://pay.asaas.com/link/abc', status: 'ACTIVE', asaas_payment_id: 'pl_123' } } }).as('postLink');
    cy.visit('/financeiro/bancos?tab=asaas');
    cy.get('#asaasSearchCustomer').type('Teste');
    cy.get('#asaasBtnListCustomers').click();
    cy.wait('@getCustomers');
    cy.get('#asaasResults').should('contain.text', 'Cliente Teste');
    cy.get('#asaasBtnListPayments').click();
    cy.wait('@getPayments');
    cy.get('#asaasResults').should('contain.text', 'CONFIRMED');
    cy.get('#asaasSaleId').type('SO-2025-0001');
    cy.get('#asaasClientId').type('10');
    cy.get('#asaasAmountCents').type('9900');
    cy.get('#asaasDueDate').type('2025-12-31');
    cy.get('#asaasBillingType').select('PIX');
    cy.get('#asaasBtnGenLink').click();
    cy.wait('@postLink');
    cy.get('#asaasGenMsg').should('contain.text', 'Link criado');
    cy.get('#asaasGenResult').should('contain.text', 'https://pay.asaas.com/link/abc');
    cy.get('#asaasStatsLinks').should('contain.text', '1');
  });

  it('Dropdown de Conta destino em Pagar.me e Itaú é populado', () => {
    cy.intercept('GET', '/api/financeiro/bancos/contas*', {
      statusCode: 200,
      body: { data: [
        { id: 10, banco: 'Itaú', agencia: '1234', conta: '000111-2', status: 'ativa' },
        { id: 11, banco: 'Santander', agencia: '4321', conta: '999888-7', status: 'ativa' }
      ] }
    }).as('getContas2');
    cy.intercept('GET', '/api/payments/settings/pagarme', { statusCode: 200, body: { has_webhook_secret: false } }).as('getPg');
    cy.intercept('GET', '/api/payments/settings/itau', { statusCode: 200, body: { has_webhook_secret: false } }).as('getItau');
    cy.visit('/financeiro/bancos?tab=pagarme');
    cy.wait('@getContas2');
    cy.wait('@getPg');
    cy.get('#pgTargetAccountId').should('exist');
    cy.get('#pgTargetAccountId').find('option').should('have.length.at.least', 2);
    cy.visit('/financeiro/bancos?tab=itau');
    cy.wait('@getItau');
    cy.get('#itauTargetAccountId').should('exist');
    cy.get('#itauTargetAccountId').find('option').should('have.length.at.least', 2);
  });

  it('Copia endpoints de Pagar.me e Itaú', () => {
    cy.visit('/financeiro/bancos?tab=pagarme');
    cy.window().then((win) => {
      win.navigator.clipboard = { writeText: () => Promise.resolve() };
      cy.stub(win, 'alert').as('alert');
    });
    cy.get('#pgEndpoint').invoke('text').then((txt) => {
      expect(txt).to.include('/api/payments/webhooks/pagarme');
    });
    cy.get('#btnCopyPg').click();
    cy.get('@alert').should('have.been.calledWith', 'Endpoint copiado');

    cy.visit('/financeiro/bancos?tab=itau');
    cy.window().then((win) => {
      win.navigator.clipboard = { writeText: () => Promise.resolve() };
      cy.stub(win, 'alert').as('alert2');
    });
    cy.get('#itauEndpoint').invoke('text').then((txt) => {
      expect(txt).to.include('/api/payments/webhooks/itau');
    });
    cy.get('#btnCopyItau').click();
    cy.get('@alert2').should('have.been.calledWith', 'Endpoint copiado');
  });

  it('Simula webhooks Pagar.me e Itaú', () => {
    // Pagar.me
    cy.visit('/financeiro/bancos?tab=pagarme');
    const pgPayload = {
      id: 'ev_test_pg',
      type: 'transaction.paid',
      data: { object: { amount: 1000, status: 'paid' } },
    };

    cy.intercept('POST', '/api/payments/webhooks/pagarme', (req) => {
      expect(req.headers['content-type']).to.include('application/json');
      expect(req.body).to.have.property('type');
      req.reply({ statusCode: 200, body: { ok: true } });
    }).as('pgWebhook');

    cy.window().then((win) =>
      win.fetch('/api/payments/webhooks/pagarme', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(pgPayload),
      })
    );
    cy.wait('@pgWebhook');

    // Itaú
    cy.visit('/financeiro/bancos?tab=itau');
    const itauPayload = {
      event: 'pix.received',
      value: '10.00',
      e2eId: 'ABC123',
    };

    cy.intercept('POST', '/api/payments/webhooks/itau', (req) => {
      expect(req.headers['content-type']).to.include('application/json');
      expect(req.body).to.have.property('event');
      req.reply({ statusCode: 200, body: { ok: true } });
    }).as('itauWebhook');

    cy.window().then((win) =>
      win.fetch('/api/payments/webhooks/itau', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(itauPayload),
      })
    );
    cy.wait('@itauWebhook');
  });
});