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

describe("customers management - create and edit", () => {
  beforeEach(() => {
    cy.setAuthCookies();
  });

  it("validates required fields on create", () => {
    cy.intercept("GET", "**/api/proxy/companies**", {
      statusCode: 200,
      body: { success: true, message: "ok", data: { companies: [] } },
    }).as("getCompanies");

    cy.visit("/customers/create");
    cy.wait("@getCompanies");

    cy.get('button[type="submit"]').click();
    cy.contains("This field is required").should("be.visible");
  });

  it("validates invalid email on create", () => {
    cy.intercept("GET", "**/api/proxy/companies**", {
      statusCode: 200,
      body: { success: true, message: "ok", data: { companies: [] } },
    }).as("getCompanies");

    cy.visit("/customers/create");
    cy.wait("@getCompanies");

    cy.get('input[name="username"]').type("qauser");
    cy.get('input[name="email"]').type("not-an-email");
    cy.get('select[name="role"]').select("admin");
    cy.get('input[name="password"]').type("Secret123!");
    cy.get('select[name="type"]').select("individual");
    cy.get('button[type="submit"]').click();

    cy.contains("Email address is invalid").should("be.visible");
  });

  it("creates customer and sends expected payload", () => {
    cy.intercept("GET", "**/api/proxy/companies**", (req) => {
      req.reply({
        statusCode: 200,
        body: {
          success: true,
          message: "ok",
          data: {
            companies: [
              { id: "comp-1", name: "Acme" },
              { id: "comp-2", name: "Globex" },
            ],
          },
        },
      });
    }).as("getCompanies");

    cy.intercept("POST", "**/api/proxy/customers", (req) => {
      expect(req.body).to.include({
        username: "newcustomer",
        email: "newcustomer@example.com",
        role: "admin",
        type: "company",
      });
      req.reply({
        statusCode: 201,
        body: { success: true, message: "Customer created successfully", data: {} },
      });
    }).as("createCustomer");

    cy.intercept("GET", "**/api/proxy/customers**", {
      statusCode: 200,
      body: {
        success: true,
        message: "ok",
        data: { customers: [] },
        meta: { offset: 0, limit: 10, total: 0, pages: 1, page: 1 },
      },
    }).as("getCustomersAfterCreate");

    cy.visit("/customers/create");
    cy.wait("@getCompanies");

    cy.get('input[name="username"]').type("newcustomer");
    cy.get('input[name="email"]').type("newcustomer@example.com");
    cy.get('select[name="role"]').select("admin");
    cy.get('input[name="password"]').type("Secret123!");
    cy.get('select[name="type"]').select("company");
    cy.get('button[type="submit"]').click();

    cy.wait("@createCustomer");
    cy.location("pathname").should("eq", "/customers");
    cy.wait("@getCustomersAfterCreate");
  });

  it("loads edit page with customer details and updates customer", () => {
    const customerId = "507f1f77bcf86cd799439155";
    const customerDetails = {
      id: customerId,
      username: "existingcustomer",
      email: "existing@example.com",
      full_name: "Existing Customer",
      phone: "1234567890",
      role: "analyst",
      type: "individual",
      companies: [{ id: "comp-2", name: "Globex" }],
      status: "active",
      created_at: 1710001000,
      updated_at: 1710001500,
    };

    cy.intercept("GET", "**/api/proxy/companies**", {
      statusCode: 200,
      body: {
        success: true,
        message: "ok",
        data: {
          companies: [
            { id: "comp-1", name: "Acme" },
            { id: "comp-2", name: "Globex" },
          ],
        },
      },
    }).as("getCompanies");

    cy.intercept("GET", `**/api/proxy/customers/${customerId}`, {
      statusCode: 200,
      body: { success: true, message: "ok", data: customerDetails },
    }).as("getCustomerDetails");

    cy.intercept("PUT", `**/api/proxy/customers/${customerId}`, (req) => {
      expect(req.body).to.include({
        username: "existingcustomer",
        email: "updated@example.com",
        role: "admin",
        type: "company",
      });
      req.reply({
        statusCode: 200,
        body: { success: true, message: "Customer updated successfully", data: {} },
      });
    }).as("updateCustomer");

    cy.intercept("GET", "**/api/proxy/customers**", {
      statusCode: 200,
      body: {
        success: true,
        message: "ok",
        data: { customers: [] },
        meta: { offset: 0, limit: 10, total: 0, pages: 1, page: 1 },
      },
    }).as("getCustomersAfterUpdate");

    cy.visit(`/customers/edit/${customerId}`);
    cy.wait("@getCustomerDetails");
    cy.wait("@getCompanies");

    cy.get('input[name="username"]').should("have.value", "existingcustomer");
    cy.get('input[name="email"]').should("have.value", "existing@example.com");
    cy.get('select[name="role"]').should("have.value", "analyst");
    cy.get('select[name="type"]').should("have.value", "individual");

    cy.get('input[name="email"]').clear().type("updated@example.com");
    cy.get('select[name="role"]').select("admin");
    cy.get('select[name="type"]').select("company");
    cy.get('button[type="submit"]').click();

    cy.wait("@updateCustomer");
    cy.location("pathname").should("eq", "/customers");
    cy.wait("@getCustomersAfterUpdate");
  });
});
