// Helper functions for discount codes E2E tests

export interface DiscountCodeData {
  code: string;
  name: string;
  description?: string;
  type: "percentage" | "fixed" | "fee_percentage";
  value: string;
  status: "active" | "inactive";
  applicationLevel:
    | "invoice"
    | "category"
    | "product"
    | "shipping"
    | "product_fee";
  minPurchaseAmount?: string;
  maxDiscountAmount?: string;
  usageLimit?: string;
  userUsageLimit?: string;
  singleUse?: boolean;
  validFrom?: string;
  validTo?: string;
  userGroup?: "new" | "loyal" | "all";
  newUsersOnly?: boolean;
  loyalUsersOnly?: boolean;
  campaign?: string;
  category?: string;
}

declare global {
  namespace Cypress {
    interface Chainable {
      createDiscountCode(data: DiscountCodeData): Chainable<void>;
      fillBasicDiscountInfo(data: Partial<DiscountCodeData>): Chainable<void>;
      fillDiscountSettings(data: Partial<DiscountCodeData>): Chainable<void>;
      fillUserRestrictions(data: Partial<DiscountCodeData>): Chainable<void>;
      submitDiscountForm(): Chainable<void>;
      verifyDiscountCreation(): Chainable<void>;
      navigateToCreateDiscount(): Chainable<void>;
      searchDiscountCode(code: string): Chainable<void>;
      clearDiscountFilters(): Chainable<void>;
    }
  }
}

// Navigate to create discount page
Cypress.Commands.add("navigateToCreateDiscount", () => {
  cy.visit("/discount-codes");
  cy.waitForLoading();
  cy.getByTestId("create-discount-button").click();
  cy.url().should("include", "/discount-codes/create");
});

// Fill basic discount information
Cypress.Commands.add(
  "fillBasicDiscountInfo",
  (data: Partial<DiscountCodeData>) => {
    if (data.code) {
      cy.getByTestId("discount-code-input").clear().type(data.code);
    }
    if (data.name) {
      cy.getByTestId("discount-name-input").clear().type(data.name);
    }
    if (data.description) {
      cy.getByTestId("discount-description-textarea")
        .clear()
        .type(data.description);
    }
  }
);

// Fill discount settings
Cypress.Commands.add(
  "fillDiscountSettings",
  (data: Partial<DiscountCodeData>) => {
    if (data.type) {
      cy.getByTestId("discount-type-select").select(data.type);
    }
    if (data.value) {
      cy.getByTestId("discount-value-input").clear().type(data.value);
    }
    if (data.status) {
      cy.getByTestId("discount-status-select").select(data.status);
    }
    if (data.applicationLevel) {
      cy.getByTestId("discount-application-level-select").select(
        data.applicationLevel
      );
    }
    if (data.minPurchaseAmount) {
      cy.get('input[name="min_purchase_amount"]')
        .clear()
        .type(data.minPurchaseAmount);
    }
    if (data.maxDiscountAmount) {
      cy.get('input[name="max_discount_amount"]')
        .clear()
        .type(data.maxDiscountAmount);
    }
    if (data.usageLimit) {
      cy.get('input[name="usage_limit"]').clear().type(data.usageLimit);
    }
    if (data.userUsageLimit) {
      cy.get('input[name="user_usage_limit"]')
        .clear()
        .type(data.userUsageLimit);
    }
    if (data.singleUse) {
      cy.get('input[name="single_use"]').check();
    }
    if (data.validFrom) {
      cy.get('input[name="valid_from"]').type(data.validFrom);
    }
    if (data.validTo) {
      cy.get('input[name="valid_to"]').type(data.validTo);
    }
  }
);

// Fill user restrictions
Cypress.Commands.add(
  "fillUserRestrictions",
  (data: Partial<DiscountCodeData>) => {
    if (data.userGroup) {
      cy.get('select[name="user_restrictions.user_group"]').select(
        data.userGroup
      );
    }
    if (data.newUsersOnly) {
      cy.get('input[name="user_restrictions.new_users_only"]').check();
    }
    if (data.loyalUsersOnly) {
      cy.get('input[name="user_restrictions.loyal_users_only"]').check();
    }
    if (data.campaign) {
      cy.get('input[name="meta.campaign"]').clear().type(data.campaign);
    }
    if (data.category) {
      cy.get('input[name="meta.category"]').clear().type(data.category);
    }
  }
);

// Submit discount form
Cypress.Commands.add("submitDiscountForm", () => {
  cy.getByTestId("submit-discount-button").click();
});

// Verify discount creation
Cypress.Commands.add("verifyDiscountCreation", () => {
  cy.url().should("include", "/discount-codes");
  cy.url().should("not.include", "/create");
  cy.url().should("not.include", "/edit");
});

// Create complete discount code
Cypress.Commands.add("createDiscountCode", (data: DiscountCodeData) => {
  cy.navigateToCreateDiscount();
  cy.fillBasicDiscountInfo(data);
  cy.fillDiscountSettings(data);
  cy.fillUserRestrictions(data);
  cy.submitDiscountForm();
  cy.verifyDiscountCreation();
});

// Search for discount code
Cypress.Commands.add("searchDiscountCode", (code: string) => {
  cy.get('input[placeholder*="جستجو"]').clear().type(code);
  cy.wait(500); // Wait for search to filter
});

// Clear discount filters
Cypress.Commands.add("clearDiscountFilters", () => {
  cy.contains("پاک کردن فیلترها").click();
  cy.get('input[placeholder*="جستجو"]').should("have.value", "");
});

// Predefined discount code templates for testing
export const discountTemplates = {
  basicPercentage: {
    code: "BASIC20",
    name: "Basic 20% Discount",
    description: "Basic percentage discount for testing",
    type: "percentage" as const,
    value: "20",
    status: "active" as const,
    applicationLevel: "invoice" as const,
  },

  fixedAmount: {
    code: "FIXED50K",
    name: "Fixed 50K Discount",
    description: "Fixed amount discount for testing",
    type: "fixed" as const,
    value: "50000",
    status: "active" as const,
    applicationLevel: "invoice" as const,
    minPurchaseAmount: "100000",
  },

  feePercentage: {
    code: "FEERED10",
    name: "Fee Reduction 10%",
    description: "Fee percentage reduction for testing",
    type: "fee_percentage" as const,
    value: "10",
    status: "active" as const,
    applicationLevel: "product_fee" as const,
  },

  loyalUsers: {
    code: "LOYAL25",
    name: "Loyal Users 25%",
    description: "Discount for loyal users only",
    type: "percentage" as const,
    value: "25",
    status: "active" as const,
    applicationLevel: "invoice" as const,
    userGroup: "loyal" as const,
    loyalUsersOnly: true,
  },

  newUsers: {
    code: "WELCOME15",
    name: "Welcome New Users",
    description: "Welcome discount for new users",
    type: "percentage" as const,
    value: "15",
    status: "active" as const,
    applicationLevel: "invoice" as const,
    userGroup: "new" as const,
    newUsersOnly: true,
    singleUse: true,
  },

  timeBasedDiscount: {
    code: "SUMMER24",
    name: "Summer Sale 2024",
    description: "Summer sale discount with time constraints",
    type: "percentage" as const,
    value: "30",
    status: "active" as const,
    applicationLevel: "invoice" as const,
    validFrom: "2024-06-01T00:00",
    validTo: "2024-08-31T23:59",
    usageLimit: "1000",
    userUsageLimit: "1",
    campaign: "summer_sale_2024",
    category: "seasonal",
  },
};

// API response mocks
export const apiMocks = {
  successfulCreation: (data: Partial<DiscountCodeData>) => ({
    statusCode: 201,
    body: {
      id: Math.floor(Math.random() * 1000),
      code: data.code,
      name: data.name,
      description: data.description,
      type: data.type,
      value: parseFloat(data.value || "0"),
      status: data.status,
      application_level: data.applicationLevel,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    },
  }),

  validationError: {
    statusCode: 400,
    body: {
      message: "کد تخفیف تکراری است",
      errors: {
        code: ["این کد قبلاً استفاده شده است"],
      },
    },
  },

  serverError: {
    statusCode: 500,
    body: {
      message: "خطای سرور",
    },
  },

  discountsList: {
    statusCode: 200,
    body: {
      discount_codes: [
        {
          id: 1,
          code: "SAVE20",
          name: "20% Off Discount",
          description: "Get 20% off on your purchase",
          type: "percentage",
          value: 20,
          status: "active",
          application_level: "invoice",
          created_at: "2024-01-01T00:00:00Z",
        },
      ],
      total: 1,
      page: 1,
      limit: 20,
      total_pages: 1,
    },
  },
};
