/// <reference types="cypress" />
import { makeAdmin } from "../../support/admin-fixtures";

describe("admins management - create, edit, delete, status", () => {
  beforeEach(() => {
    cy.setAuthCookies();
    cy.mockAdminsList({ users: [makeAdmin()] });
  });

  it("validates create form required fields and invalid email", () => {
    cy.visit("/admins/create");
    cy.getByCy("admin-form-submit-button").click();

    cy.contains("This field is required").should("be.visible");
    cy.getByCy("admin-form-email-input").type("invalid-email");
    cy.getByCy("admin-form-submit-button").click();
    cy.contains("Email address is invalid").should("be.visible");
  });

  it("handles duplicate username response on create", () => {
    cy.mockCreateAdmin({
      statusCode: 409,
      body: { error: { message: "Username already exists" } },
      alias: "createAdminConflict",
    });

    cy.visit("/admins/create");
    cy.getByCy("admin-form-full-name-input").type("Create Admin Name");
    cy.getByCy("admin-form-username-input").type("existinguser");
    cy.getByCy("admin-form-email-input").type("existing-user@example.com");
    cy.getByCy("admin-form-password-input").type("Secret123!");
    cy.getByCy("admin-form-submit-button").click();

    cy.wait("@createAdminConflict");
    cy.contains("Username already exists").should("be.visible");
    cy.location("pathname").should("eq", "/admins/create");
  });

  it("creates admin successfully and shows new row + success toast", () => {
    cy.mockCreateAdmin({ alias: "createAdminSuccess" });
    cy.mockAdminsList({
      alias: "getAdminsAfterCreate",
      users: [makeAdmin({}, 1), makeAdmin({ id: "507f1f77bcf86cd799439077", full_name: "New Admin" }, 7)],
    });

    cy.visit("/admins/create");
    cy.getByCy("admin-form-full-name-input").type("New Admin");
    cy.getByCy("admin-form-username-input").type("newadmin");
    cy.getByCy("admin-form-email-input").type("newadmin@example.com");
    cy.getByCy("admin-form-password-input").type("Secret123!");
    cy.getByCy("admin-form-submit-button").click();

    cy.wait("@createAdminSuccess");
    cy.location("pathname").should("eq", "/admins");
    cy.wait("@getAdminsAfterCreate");
    cy.contains("New Admin").should("be.visible");
    cy.contains(/success|created/i).should("be.visible");
  });

  it("opens edit form prefilled and updates admin successfully", () => {
    const admin = makeAdmin(
      {
        id: "507f1f77bcf86cd799439055",
        full_name: "Old Name",
        username: "oldnameadmin",
      },
      5,
    );
    cy.mockAdminsList({ users: [admin] });
    cy.intercept("GET", `**/api/proxy/users/${admin.id}`, {
      statusCode: 200,
      body: { success: true, message: "ok", data: admin },
    }).as("getAdminDetails");
    cy.mockUpdateAdmin(admin.id, { alias: "updateAdminSuccess" });

    cy.visit("/admins");
    cy.contains("Old Name").should("be.visible");
    cy.getByCy(`admins-row-edit-${admin.id}`).click();
    cy.wait("@getAdminDetails");
    cy.location("pathname").should("eq", `/admins/edit/${admin.id}`);
    cy.getByCy("admin-form-full-name-input").should("have.value", "Old Name");

    cy.getByCy("admin-form-full-name-input").clear().type("Updated Name");
    cy.mockAdminsList({
      alias: "getAdminsAfterUpdate",
      users: [makeAdmin({ ...admin, full_name: "Updated Name" }, 5)],
    });
    cy.getByCy("admin-form-submit-button").click();

    cy.wait("@updateAdminSuccess");
    cy.location("pathname").should("eq", "/admins");
    cy.wait("@getAdminsAfterUpdate");
    cy.contains("Updated Name").should("be.visible");
  });

  it("shows delete confirmation and supports cancel + confirm", () => {
    const admin = makeAdmin({ id: "507f1f77bcf86cd799439066", full_name: "Delete Me" }, 6);
    cy.mockAdminsList({ users: [admin] });

    cy.visit("/admins");
    cy.wait("@getAdmins");
    cy.getByCy(`admins-row-delete-${admin.id}`).click();
    cy.getByCy("confirmation-modal").should("be.visible");
    cy.getByCy("confirmation-modal-cancel").click();
    cy.getByCy("confirmation-modal").should("not.exist");

    cy.mockDeleteAdmin(admin.id, { alias: "deleteAdminSuccess" });
    cy.mockAdminsList({ alias: "getAdminsAfterDelete", users: [] });
    cy.getByCy(`admins-row-delete-${admin.id}`).click();
    cy.getByCy("confirmation-modal-confirm").click();

    cy.wait("@deleteAdminSuccess");
    cy.wait("@getAdminsAfterDelete");
    cy.getByCy("empty-list-message").should("be.visible");
  });

  it("changes admin status and persists after refresh", () => {
    const admin = makeAdmin({ id: "507f1f77bcf86cd799439088", status: "inactive" }, 8);
    cy.mockAdminsList({ users: [admin] });

    cy.visit("/admins");
    cy.wait("@getAdmins");
    cy.getByCy(`admins-row-manage-status-${admin.id}`).click();
    cy.getByCy("modal-content").should("be.visible");
    cy.getByCy("admins-change-status-select").select("active");

    cy.mockChangeAdminStatus(admin.id, { alias: "statusUpdated" });
    cy.mockAdminsList({
      alias: "getAdminsAfterStatusChange",
      users: [makeAdmin({ ...admin, status: "active" }, 8)],
    });

    cy.getByCy("modal-confirm-button").click();
    cy.wait("@statusUpdated");
    cy.wait("@getAdminsAfterStatusChange");
    cy.getByCy(`admins-table-row-${admin.id}`).within(() => {
      cy.getByCy("admins-row-status").should("contain", "active");
    });

    cy.reload();
    cy.wait("@getAdminsAfterStatusChange");
    cy.getByCy(`admins-table-row-${admin.id}`).within(() => {
      cy.getByCy("admins-row-status").should("contain", "active");
    });
  });

  it("prevents duplicate create submission while request is pending", () => {
    cy.intercept("POST", "**/api/proxy/users", (req) => {
      req.reply({
        delay: 1400,
        statusCode: 201,
        body: { success: true, message: "created", data: {} },
      });
    }).as("slowCreateAdmin");

    cy.visit("/admins/create");
    cy.getByCy("admin-form-full-name-input").type("Slow Admin");
    cy.getByCy("admin-form-username-input").type("slowadmin");
    cy.getByCy("admin-form-email-input").type("slowadmin@example.com");
    cy.getByCy("admin-form-password-input").type("Secret123!");
    cy.getByCy("admin-form-submit-button").click();
    cy.getByCy("admin-form-submit-button").should("be.disabled");
    cy.getByCy("admin-form-submit-button").find("div.animate-spin").should("exist");

    cy.wait("@slowCreateAdmin");
    cy.get("@slowCreateAdmin.all").should("have.length", 1);
  });
});
