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

describe("TM-389 - prevent duplicate create customer request", () => {
  let createRequestCount = 0;
  const fillRequiredFormFields = () => {
    cy.get('input[name="username"]').type("tm389user");
    cy.get('input[name="email"]').type("tm389@example.com");
    cy.get('select[name="role"]').select("admin");
    cy.get('input[name="password"]').type("Secret123!");
    cy.get('select[name="type"]').select("individual");
  };

  beforeEach(() => {
    createRequestCount = 0;

    cy.intercept("GET", "**/api/proxy/companies**", {
      statusCode: 200,
      body: {
        success: true,
        message: "ok",
        data: {
          companies: [
            {
              id: "507f1f77bcf86cd799439011",
              name: "Acme Company",
              email: "acme@example.com",
              phone: "1234567890",
              website: "https://acme.example.com",
              type: "private",
              description: "Test company",
              founded_year: 2020,
              employee_count: 50,
              annual_revenue: 100000,
              currency: "USD",
              industry: "Tech",
              language: "en",
              tax_id: "TAX-001",
              registration_number: "REG-001",
              timezone: "UTC",
              address: {
                street: "Street 1",
                city: "City",
                state: "State",
                postal_code: "12345",
                country: "Country",
              },
              contact_person: {
                full_name: "John Doe",
                first_name: "John",
                last_name: "Doe",
                email: "john@example.com",
                phone: "1234567890",
                mobile: "1234567890",
                position: "Manager",
                is_primary: true,
              },
              tags: {
                keywords: [],
                categories: [],
                specializations: [],
                certifications: [],
                cpv_codes: [],
              },
            },
          ],
          offset: 0,
          limit: 10,
          total: 1,
        },
      },
    }).as("getCompanies");

    cy.intercept("POST", "**/api/proxy/customers*", (req) => {
      createRequestCount += 1;
      req.reply({
        delay: 1200,
        statusCode: 201,
        body: {
          success: true,
          message: "created",
          data: {},
        },
      });
    }).as("createCustomer");
  });

  it("sends only one create request even when submit is clicked repeatedly", () => {
    cy.visit("/customers/create");

    cy.wait("@getCompanies");

    fillRequiredFormFields();

    cy.get('button[type="submit"]').as("submitButton");
    cy.get("@submitButton").should("not.be.disabled");
    cy.get("@submitButton").click();

    // Fire extra clicks while request is in-flight to simulate impatient taps.
    cy.get("@submitButton").then(($button) => {
      const button = $button.get(0) as HTMLButtonElement;
      button.click();
      button.click();
      button.click();
    });

    cy.get('button[type="submit"]').should("be.disabled");
    cy.wait("@createCustomer");
    cy.get("@createCustomer.all").should("have.length", 1);
    cy.then(() => {
      expect(createRequestCount).to.eq(1);
    });
  });

  it("does not send another create request when submit is clicked again before response", () => {
    cy.visit("/customers/create");

    cy.wait("@getCompanies");
    fillRequiredFormFields();

    cy.get('button[type="submit"]').as("submitButton");
    cy.get("@submitButton").click();

    cy.get("@submitButton").then(($button) => {
      const button = $button.get(0) as HTMLButtonElement;
      button.click();
    });

    // Ensure we are still in-flight and no duplicate request was fired.
    cy.wait(300);
    cy.get("@createCustomer.all").should("have.length", 1);
    cy.then(() => {
      expect(createRequestCount).to.eq(1);
    });

    cy.wait("@createCustomer");
  });
});
