// Custom Cypress commands for auth and seeding data

Cypress.Commands.add('login', (email = 'admin@local', password = 'admin123') => {
  cy.visit('/login');
  cy.get('#email').should('be.visible').clear().type(email);
  cy.get('#password').should('be.visible').clear().type(password, { log: false });
  cy.intercept('POST', '/api/auth/login').as('login');
  cy.get('#loginBtn').click();
  cy.wait('@login').its('response.statusCode').should('eq', 200);
  cy.getCookie('auth_token').should('exist');
});

function authHeadersFromCookie() {
  return cy.getCookie('auth_token').then((c) => {
    const token = c?.value;
    return {
      Authorization: token ? `Bearer ${token}` : undefined,
      'x-tenant-id': 'default'
    };
  });
}

Cypress.Commands.add('seedSupplier', (opts = {}) => {
  const name = opts.name || 'Fornecedor Cypress';
  const email = opts.email || 'supplier@example.com';
  const cnpj = opts.cnpj || '11.222.333/0001-44';
  return authHeadersFromCookie().then((headers) => {
    return cy.request({
      method: 'POST',
      url: '/api/cadastros/fornecedores',
      headers,
      body: { nome: name, email, cnpj }
    }).then((resp) => {
      expect(resp.status).to.be.oneOf([200, 201]);
      const id = resp.body?.data?.id || resp.body?.id;
      expect(id, 'supplier id').to.be.a('number');
      return { id, name, email };
    });
  });
});

Cypress.Commands.add('seedProduct', (opts = {}) => {
  const codigo = opts.codigo || 'CYP-ITEM-001';
  const preco = opts.preco ?? 10.5;
  const nome = opts.nome || 'Item Cypress';
  return authHeadersFromCookie().then((headers) => {
    return cy.request({
      method: 'POST',
      url: '/api/produtos',
      headers,
      body: { codigo, preco, nome }
    }).then((resp) => {
      expect(resp.status).to.be.oneOf([200, 201]);
      const id = resp.body?.data?.id || resp.body?.id;
      expect(id, 'product id').to.be.a('number');
      return { id, codigo, nome };
    });
  });
});