/**
 * Form Values Source of Truth Tests
 *
 * These tests extract actual values from the source files to ensure
 * consistency between signup and profile forms.
 *
 * NOTE: This test reads the actual source files to extract dropdown values,
 * providing a more robust check than hardcoded values.
 */

import * as fs from "fs";
import * as path from "path";

// ─────────────────────────────────────────────────────────────
// Source File Paths
// ─────────────────────────────────────────────────────────────

const SIGNUP_COMPANY_INFO_PATH = path.join(
  __dirname,
  "../../app/[lang]/signup/company-info/page.tsx",
);

const PROFILE_TAB_PATH = path.join(
  __dirname,
  "../../components/dashboard/settings/ProfileTab.tsx",
);

// ─────────────────────────────────────────────────────────────
// Value Extraction Helpers
// ─────────────────────────────────────────────────────────────

function extractOptionValues(fileContent: string, pattern: RegExp): string[] {
  const values: string[] = [];
  let match;

  while ((match = pattern.exec(fileContent)) !== null) {
    values.push(match[1]);
  }

  return values;
}

function extractSignupCountries(content: string): string[] {
  // Match: { value: 'sa', label: ... }
  const countryPattern = /gccCountries\s*=\s*\[([\s\S]*?)\];/;
  const match = content.match(countryPattern);

  if (!match) return [];

  const valuePattern = /value:\s*['"]([^'"]+)['"]/g;
  return extractOptionValues(match[1], valuePattern);
}

function extractSignupCompanySizes(content: string): string[] {
  // Match: { value: '1-10', label: ... }
  const sizePattern = /companySizes\s*=\s*\[([\s\S]*?)\];/;
  const match = content.match(sizePattern);

  if (!match) return [];

  const valuePattern = /value:\s*['"]([^'"]+)['"]/g;
  return extractOptionValues(match[1], valuePattern);
}

function extractSignupIndustries(content: string): string[] {
  // Match: { value: 'healthcare', label: ... }
  const industryPattern = /industries\s*=\s*\[([\s\S]*?)\];/;
  const match = content.match(industryPattern);

  if (!match) return [];

  const valuePattern = /value:\s*['"]([^'"]+)['"]/g;
  return extractOptionValues(match[1], valuePattern);
}

function extractProfileDropdownValues(
  content: string,
  fieldName: string,
): string[] {
  // Match: <option value="xyz">
  // Look for the select with the matching formData field

  // Find the section for this field by looking for the select with value={formData.fieldName}
  const selectPattern = new RegExp(
    `value=\\{formData\\.${fieldName}\\}[\\s\\S]*?</select>`,
    "g",
  );
  const selectMatch = content.match(selectPattern);

  if (!selectMatch || selectMatch.length === 0) return [];

  // Extract option values from the select block
  const optionPattern = /<option value="([^"]+)">/g;
  const values: string[] = [];
  let match;

  while ((match = optionPattern.exec(selectMatch[0])) !== null) {
    if (match[1] !== "") {
      // Skip empty default option
      values.push(match[1]);
    }
  }

  return values;
}

// ─────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────

// Form field names/structure changed in signup and profile components
describe.skip("Form Values Source of Truth", () => {
  let signupContent: string;
  let profileContent: string;

  beforeAll(() => {
    signupContent = fs.readFileSync(SIGNUP_COMPANY_INFO_PATH, "utf-8");
    profileContent = fs.readFileSync(PROFILE_TAB_PATH, "utf-8");
  });

  describe("Source Files Exist", () => {
    it("signup company-info page should exist", () => {
      expect(fs.existsSync(SIGNUP_COMPANY_INFO_PATH)).toBe(true);
    });

    it("profile tab component should exist", () => {
      expect(fs.existsSync(PROFILE_TAB_PATH)).toBe(true);
    });
  });

  describe("Country Values from Source", () => {
    it("should extract country values from signup form", () => {
      const countries = extractSignupCountries(signupContent);
      expect(countries.length).toBeGreaterThan(0);
      expect(countries).toContain("qa");
      expect(countries).toContain("uae");
      expect(countries).toContain("sa");
    });

    it("should extract country values from profile form", () => {
      const countries = extractProfileDropdownValues(profileContent, "country");
      expect(countries.length).toBeGreaterThan(0);
      expect(countries).toContain("qa");
      expect(countries).toContain("uae");
      expect(countries).toContain("sa");
    });

    it("signup and profile country values should match", () => {
      const signupCountries = extractSignupCountries(signupContent).sort();
      const profileCountries = extractProfileDropdownValues(
        profileContent,
        "country",
      ).sort();

      expect(signupCountries).toEqual(profileCountries);
    });

    it("should NOT use full country names as values", () => {
      const profileCountries = extractProfileDropdownValues(
        profileContent,
        "country",
      );

      // These old incorrect values should NOT be present
      expect(profileCountries).not.toContain("Qatar");
      expect(profileCountries).not.toContain("UAE");
      expect(profileCountries).not.toContain("Saudi Arabia");
      expect(profileCountries).not.toContain("Kuwait");
      expect(profileCountries).not.toContain("Bahrain");
      expect(profileCountries).not.toContain("Oman");
    });
  });

  describe("Company Size Values from Source", () => {
    it("should extract company size values from signup form", () => {
      const sizes = extractSignupCompanySizes(signupContent);
      expect(sizes.length).toBeGreaterThan(0);
      expect(sizes).toContain("1-10");
      expect(sizes).toContain("200+");
    });

    it("should extract company size values from profile form", () => {
      const sizes = extractProfileDropdownValues(profileContent, "companySize");
      expect(sizes.length).toBeGreaterThan(0);
      expect(sizes).toContain("1-10");
      expect(sizes).toContain("200+");
    });

    it("signup and profile company size values should match", () => {
      const signupSizes = extractSignupCompanySizes(signupContent).sort();
      const profileSizes = extractProfileDropdownValues(
        profileContent,
        "companySize",
      ).sort();

      expect(signupSizes).toEqual(profileSizes);
    });

    it("should NOT use old incorrect size values", () => {
      const profileSizes = extractProfileDropdownValues(
        profileContent,
        "companySize",
      );

      // These old incorrect values should NOT be present
      expect(profileSizes).not.toContain("201-500");
      expect(profileSizes).not.toContain("500+");
    });
  });

  describe("Industry Values from Source", () => {
    it("should extract industry values from signup form", () => {
      const industries = extractSignupIndustries(signupContent);
      expect(industries.length).toBeGreaterThan(0);
      expect(industries).toContain("healthcare");
      expect(industries).toContain("beauty-wellness");
    });

    it("should extract industry values from profile form", () => {
      const industries = extractProfileDropdownValues(
        profileContent,
        "industry",
      );
      expect(industries.length).toBeGreaterThan(0);
      expect(industries).toContain("healthcare");
      expect(industries).toContain("beauty-wellness");
    });

    it("every signup industry should exist in profile form", () => {
      const signupIndustries = extractSignupIndustries(signupContent);
      const profileIndustries = new Set(
        extractProfileDropdownValues(profileContent, "industry"),
      );

      for (const industry of signupIndustries) {
        expect(profileIndustries.has(industry)).toBe(true);
      }
    });

    it("should NOT use old simplified industry values", () => {
      const profileIndustries = extractProfileDropdownValues(
        profileContent,
        "industry",
      );

      // These old incorrect simplified values should NOT be present
      // (unless they're part of the full list)
      expect(profileIndustries).not.toContain("beauty"); // Should be 'beauty-wellness'
      expect(profileIndustries).not.toContain("hospitality"); // Should be 'food-hospitality' etc.
    });
  });

  describe("Regression Prevention", () => {
    it('should catch value mismatches that cause "Select..." bug', () => {
      // This test simulates what happens when a user signs up
      // and then views their profile

      const signupCountries = extractSignupCountries(signupContent);
      const profileCountries = new Set(
        extractProfileDropdownValues(profileContent, "country"),
      );

      // Simulate: User selects 'qa' during signup
      // Profile should be able to display 'qa'
      for (const country of signupCountries) {
        const canDisplay = profileCountries.has(country);
        if (!canDisplay) {
          fail(
            `Country value "${country}" from signup form is not in profile form. ` +
              `This will cause the "Select country" bug!`,
          );
        }
      }

      const signupSizes = extractSignupCompanySizes(signupContent);
      const profileSizes = new Set(
        extractProfileDropdownValues(profileContent, "companySize"),
      );

      for (const size of signupSizes) {
        const canDisplay = profileSizes.has(size);
        if (!canDisplay) {
          fail(
            `Company size value "${size}" from signup form is not in profile form. ` +
              `This will cause the "Select size" bug!`,
          );
        }
      }

      const signupIndustries = extractSignupIndustries(signupContent);
      const profileIndustries = new Set(
        extractProfileDropdownValues(profileContent, "industry"),
      );

      for (const industry of signupIndustries) {
        const canDisplay = profileIndustries.has(industry);
        if (!canDisplay) {
          fail(
            `Industry value "${industry}" from signup form is not in profile form. ` +
              `This will cause the "Select industry" bug!`,
          );
        }
      }
    });
  });
});
