/// <reference types="cypress" />

describe('Relatórios de Vendas - UI e Exportações', () => {
  const base = 'http://localhost:8001';

  function stubFilters() {
    cy.intercept('GET', base + '/api/sales/filters', {
      products: [{ id: 1, name: 'Produto A' }, { id: 2, name: 'Produto B' }],
      regions: [{ name: 'Sul' }, { name: 'Sudeste' }],
      sellers: [{ id: 10, name: 'João' }, { id: 11, name: 'Maria' }]
    }).as('filters');
  }

  function stubAdvanced() {
    cy.intercept('GET', /\/api\/sales\/advanced.*/, {
      current: { items: [
        { date: '2025-10-01', amount_cents: 123450 },
        { date: '2025-10-02', amount_cents: 234560 }
      ] },
      previous: { items: [
        { date: '2025-09-30', amount_cents: 100000 },
        { date: '2025-10-01', amount_cents: 120000 }
      ] }
    }).as('advanced');
  }

  function stubBySeller() {
    cy.intercept('GET', /\/api\/sales\/by-seller.*/, {
      data: [
        { seller_name: 'João', orders: 12, revenue_cents: 345670, avg_ticket_cents: 28700 },
        { seller_name: 'Maria', orders: 8, revenue_cents: 210000, avg_ticket_cents: 26250 }
      ]
    }).as('bySeller');
  }

  function stubTopProducts() {
    cy.intercept('GET', /\/api\/sales\/top-products.*/, {
      data: [
        { product_id: 1, product_name: 'Produto A', items_count: 42, revenue_cents: 560000 },
        { product_id: 2, product_name: 'Produto B', items_count: 24, revenue_cents: 320000 }
      ]
    }).as('topProducts');
  }

  function stubTopRegions() {
    cy.intercept('GET', /\/api\/sales\/top-regions.*/, {
      data: [
        { region: 'Sul', orders_count: 30, revenue_cents: 400000 },
        { region: 'Sudeste', orders_count: 28, revenue_cents: 380000 }
      ]
    }).as('topRegions');
  }

  beforeEach(() => {
    // Evitar falhas por erros de console inesperados
    Cypress.on('window:before:load', (win) => {
      cy.stub(win.console, 'error').as('consoleError');
    });
    stubFilters();
    stubAdvanced();
    stubBySeller();
    stubTopProducts();
    stubTopRegions();
  });

  it('carrega a página e popula filtros', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.wait('@filters');
    cy.get('#vendasProduto').find('option').should('have.length.greaterThan', 1);
    cy.get('#vendasRegiao').find('option').should('have.length.greaterThan', 1);
    cy.get('#vendasVendedor').find('option').should('have.length.greaterThan', 1);
  });

  it('padroniza tamanho dos botões (.btn)', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.get('#btnGerarVendas')
      .should('have.class', 'btn')
      .and('have.css', 'min-height', '40px')
      .and('have.css', 'font-size', '14px');
    cy.get('#btnExportarPdfPagina')
      .should('have.class', 'btn')
      .and('have.css', 'min-height', '40px');
  });

  it('gera relatório e renderiza tabelas e gráficos', () => {
    cy.visit(base + '/relatorios/vendas');
    // Define datas explícitas para evitar valores vazios
    cy.get('#vendasDataInicio').type('2025-10-01');
    cy.get('#vendasDataFim').type('2025-10-31');
    cy.get('#btnGerarVendas').click();
    cy.wait(['@advanced', '@bySeller', '@topProducts', '@topRegions']);
    cy.get('#tbodyBySeller').find('tr').should('have.length.greaterThan', 1);
    // Top Produtos: valida colunas e percentuais
    cy.get('#tbodyTopProducts').find('tr').should('have.length', 2);
    cy.get('#tbodyTopProducts tr').first().find('td').should('have.length', 5);
    cy.get('#tbodyTopProducts tr').first().find('td').eq(0).should('have.text', '1');
    cy.get('#tbodyTopProducts tr').eq(1).find('td').eq(0).should('have.text', '2');
    cy.get('#tbodyTopProducts').closest('table').find('thead tr th').eq(4).should('contain.text', 'Percentual');
    // 560k / (560k + 320k) = 63.6%
    cy.get('#tbodyTopProducts tr').first().find('td').eq(4).should('contain.text', '63.6%');
    cy.get('#tbodyTopProducts tr').eq(1).find('td').eq(4).should('contain.text', '36.4%');

    // Top Regiões: valida colunas e percentuais
    cy.get('#tbodyTopRegions').find('tr').should('have.length', 2);
    cy.get('#tbodyTopRegions tr').first().find('td').should('have.length', 5);
    cy.get('#tbodyTopRegions tr').first().find('td').eq(0).should('have.text', '1');
    cy.get('#tbodyTopRegions tr').eq(1).find('td').eq(0).should('have.text', '2');
    cy.get('#tbodyTopRegions').closest('table').find('thead tr th').eq(4).should('contain.text', 'Percentual');
    // 400k / (400k + 380k) = 51.3%
    cy.get('#tbodyTopRegions tr').first().find('td').eq(4).should('contain.text', '51.3%');
    cy.get('#tbodyTopRegions tr').eq(1).find('td').eq(4).should('contain.text', '48.7%');
    cy.get('#chartVendasSerie').children().should('have.length.greaterThan', 0);
    cy.get('#chartTopProducts').children().should('have.length.greaterThan', 0);
    cy.get('#chartTopRegions').children().should('have.length.greaterThan', 0);
    // Gráficos devem exibir percentuais nos labels
    cy.get('#chartTopProducts').should('contain.text', '%');
    cy.get('#chartTopRegions').should('contain.text', '%');
  });

  it('exporta CSV (Vendedores, Produtos, Regiões)', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.get('#btnGerarVendas').click();
    cy.wait(['@bySeller', '@topProducts', '@topRegions']);
    cy.window().then((win) => {
      cy.stub(win.HTMLAnchorElement.prototype, 'click').as('aClick');
    });
    cy.get('#btnExportarVendasCsv').click();
    cy.get('#btnExportTopProductsCsv').click();
    cy.get('#btnExportTopRegionsCsv').click();
    cy.get('@aClick').should('have.been.called');
  });

  it('exporta PNG dos gráficos com html2canvas stubado', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.get('#btnGerarVendas').click();
    cy.wait(['@advanced', '@topProducts', '@topRegions']);
    cy.window().then((win) => {
      const fakeCanvas = win.document.createElement('canvas');
      Object.defineProperty(fakeCanvas, 'width', { value: 800 });
      Object.defineProperty(fakeCanvas, 'height', { value: 600 });
      fakeCanvas.toDataURL = () => 'data:image/png;base64,ZmFrZQ==';
      cy.stub(win, 'html2canvas').resolves(fakeCanvas);
      cy.stub(win.HTMLAnchorElement.prototype, 'click').as('aClick');
    });
    cy.get('#btnVendasSeriePng').click();
    cy.get('#btnTopProductsPng').click();
    cy.get('#btnTopRegionsPng').click();
    cy.get('@aClick').should('have.been.called');
  });

  it('exporta PDF da página (multi-página) com jsPDF stubado', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.get('#btnGerarVendas').click();
    cy.wait(['@advanced', '@bySeller', '@topProducts', '@topRegions']);
    cy.window().then((win) => {
      // html2canvas gera um canvas válido para cada card
      const mkCanvas = () => {
        const c = win.document.createElement('canvas');
        Object.defineProperty(c, 'width', { value: 800 });
        Object.defineProperty(c, 'height', { value: 600 });
        c.toDataURL = () => 'data:image/jpeg;base64,ZmFrZQ==';
        return c;
      };
      let count = 0;
      cy.stub(win, 'html2canvas').callsFake(async () => { count++; return mkCanvas(); });

      const save = cy.stub().as('pdfSave');
      const addPage = cy.stub();
      const addImage = cy.stub();
      const jsPDF = function(){ return {
        internal: { pageSize: { getWidth: () => 210, getHeight: () => 297 } },
        addPage, addImage, save
      }; };
      win.jspdf = { jsPDF };
    });
    cy.get('#btnExportarPdfPagina').click();
    cy.get('@pdfSave').should('have.been.called');
  });

  it('valida fluxo de impressão via safePrint sem erros', () => {
    cy.visit(base + '/relatorios/vendas');
    cy.window().then((win) => {
      cy.stub(win, 'print').as('winPrint');
      // Chama impressão segura (exposta globalmente por print-control.js)
      win.safePrint(1);
    });
    cy.get('@winPrint').should('have.been.called');
    cy.get('@consoleError').should('not.have.been.called');
  });
});