/**
 * Regional logic unit tests — no React, no build aliases needed.
 *
 * These tests demonstrate how to validate the decorator composition pattern
 * and logic factories in isolation. Run with: daas test
 *
 * Key insight: because logic factories are pure functions that receive config
 * as a parameter, they are trivially testable without mocking imports.
 */
import { describe, test, expect } from "vitest"
import { withCurrencySymbol, withTaxLabel } from "./decorators"
import { createRegistry } from "./registry"
import { baseFormatAmount, baseValidateAmount } from "../config/regions/default/logic"
import { createLogic as createUkLogic } from "../config/regions/uk/logic"
import { createLogic as createUsLogic } from "../config/regions/us/logic"
import { createLogic as createSgLogic } from "../config/regions/sg/logic"
import type { RegionConfig } from "./types"
import defaultRegistry from "../config/regions/default"
import ukRegistry from "../config/regions/uk"
import usRegistry from "../config/regions/us"
import sgRegistry from "../config/regions/sg"

// ── Decorator unit tests ─────────────────────────────────────────────────────

describe("withCurrencySymbol", () => {
  test("prepends symbol to formatter output", () => {
    const format = withCurrencySymbol("£")(baseFormatAmount)
    expect(format(99)).toBe("£99")
    expect(format(0)).toBe("£0")
    expect(format(1234.56)).toBe("£1234.56")
  })

  test("supports any symbol including multi-char", () => {
    const format = withCurrencySymbol("SGD ")(baseFormatAmount)
    expect(format(100)).toBe("SGD 100")
  })
})

describe("withTaxLabel", () => {
  test("appends label to formatter output", () => {
    const format = withTaxLabel("inc. VAT")(baseFormatAmount)
    expect(format(99)).toBe("99 inc. VAT")
  })

  test("composes with withCurrencySymbol", () => {
    // Composition order: withTaxLabel wraps withCurrencySymbol wraps base
    // innermost (withCurrencySymbol) runs first: 99 → "£99"
    // outermost (withTaxLabel) runs second: "£99" → "£99 inc. VAT"
    const format = withTaxLabel("inc. VAT")(withCurrencySymbol("£")(baseFormatAmount))
    expect(format(99)).toBe("£99 inc. VAT")
    expect(format(9.99)).toBe("£9.99 inc. VAT")
  })
})

// ── Base logic tests ─────────────────────────────────────────────────────────

describe("baseFormatAmount", () => {
  test("converts number to string", () => {
    expect(baseFormatAmount(99)).toBe("99")
    expect(baseFormatAmount(9.99)).toBe("9.99")
    expect(baseFormatAmount(0)).toBe("0")
  })
})

describe("baseValidateAmount", () => {
  test("returns true for positive numbers", () => {
    expect(baseValidateAmount(0.01)).toBe(true)
    expect(baseValidateAmount(99.99)).toBe(true)
    expect(baseValidateAmount(1000000)).toBe(true)
  })

  test("returns false for zero and negative", () => {
    expect(baseValidateAmount(0)).toBe(false)
    expect(baseValidateAmount(-1)).toBe(false)
    expect(baseValidateAmount(-0.01)).toBe(false)
  })
})

// ── UK logic factory tests ───────────────────────────────────────────────────

const ukConfig: RegionConfig = {
  id: "uk",
  locale: "en-GB",
  currency: "GBP",
  dateFormat: "DD/MM/YYYY",
  numberFormat: { decimal: ".", thousands: "," },
  features: { showDetailsTab: false, showAnalyticsTab: false, enableExport: false, enableOrderForm: true },
}

describe("UK logic factory", () => {
  test("formats with £ symbol and VAT label", () => {
    const logic = createUkLogic(ukConfig)
    expect(logic.formatAmount(99)).toBe("£99 inc. VAT")
    expect(logic.formatAmount(9.99)).toBe("£9.99 inc. VAT")
  })

  test("validateAmount returns false when showDetailsTab is false (data access restricted)", () => {
    const logic = createUkLogic(ukConfig)
    // UK has showDetailsTab: false — validation is gated on this flag
    expect(logic.validateAmount(99)).toBe(false)
    expect(logic.validateAmount(0.01)).toBe(false)
  })

  test("validateAmount returns true when showDetailsTab is true", () => {
    const enabledConfig = { ...ukConfig, features: { ...ukConfig.features, showDetailsTab: true } }
    const logic = createUkLogic(enabledConfig)
    expect(logic.validateAmount(99)).toBe(true)
    expect(logic.validateAmount(0)).toBe(false) // still fails base check
  })
})

// ── US logic factory tests ───────────────────────────────────────────────────

const usConfig: RegionConfig = {
  id: "us",
  locale: "en-US",
  currency: "USD",
  dateFormat: "MM/DD/YYYY",
  numberFormat: { decimal: ".", thousands: "," },
  features: { showDetailsTab: true, showAnalyticsTab: true, enableExport: true, enableOrderForm: true },
}

describe("US logic factory", () => {
  test("formats with $ symbol, no tax label", () => {
    const logic = createUsLogic(usConfig)
    expect(logic.formatAmount(99)).toBe("$99")
    expect(logic.formatAmount(9.99)).toBe("$9.99")
  })

  test("validates with standard positive check", () => {
    const logic = createUsLogic(usConfig)
    expect(logic.validateAmount(99)).toBe(true)
    expect(logic.validateAmount(0)).toBe(false)
    expect(logic.validateAmount(-5)).toBe(false)
  })
})

// ── Singapore logic factory tests ───────────────────────────────────────────
// Minimal override example: only currency symbol changes.

const sgConfig: RegionConfig = {
  id: "sg",
  locale: "en-SG",
  currency: "SGD",
  dateFormat: "DD/MM/YYYY",
  numberFormat: { decimal: ".", thousands: "," },
  features: { showDetailsTab: true, showAnalyticsTab: false, enableExport: true, enableOrderForm: true },
}

describe("SG logic factory", () => {
  test("formats with SGD prefix", () => {
    const logic = createSgLogic(sgConfig)
    expect(logic.formatAmount(99)).toBe("SGD 99")
    expect(logic.formatAmount(9.99)).toBe("SGD 9.99")
  })

  test("validates with standard positive check (inherits from default)", () => {
    const logic = createSgLogic(sgConfig)
    expect(logic.validateAmount(99)).toBe(true)
    expect(logic.validateAmount(0)).toBe(false)
  })
})

// ── Composition pattern demonstration ───────────────────────────────────────

describe("decorator composition is order-dependent", () => {
  test("UK pattern: symbol applied first, label appended second", () => {
    // withTaxLabel(withCurrencySymbol(base)):
    //   base(99) → "99" → currency → "£99" → tax → "£99 inc. VAT"
    const format = withTaxLabel("inc. VAT")(withCurrencySymbol("£")(baseFormatAmount))
    expect(format(99)).toBe("£99 inc. VAT")
  })

  test("two labels stacked: inner label appears first in output", () => {
    // Order matters when two labels are stacked — they appear in application order.
    // withTaxLabel("+VAT")(withTaxLabel("+GST")(base)):
    //   base(99) → "99" → +GST → "99 +GST" → +VAT → "99 +GST +VAT"
    const gstThenVat = withTaxLabel("+VAT")(withTaxLabel("+GST")(baseFormatAmount))
    expect(gstThenVat(99)).toBe("99 +GST +VAT")

    // Reversed: inner is +VAT, outer is +GST → "99 +VAT +GST"
    const vatThenGst = withTaxLabel("+GST")(withTaxLabel("+VAT")(baseFormatAmount))
    expect(vatThenGst(99)).toBe("99 +VAT +GST")
  })

  test("two symbols stacked: outer symbol wraps the already-prefixed string", () => {
    // withCurrencySymbol("$")(withCurrencySymbol("£")(base)):
    //   base(99) → "99" → £ → "£99" → $ → "$£99"
    const poundThenDollar = withCurrencySymbol("$")(withCurrencySymbol("£")(baseFormatAmount))
    expect(poundThenDollar(99)).toBe("$£99")

    // Reversed: "£$99"
    const dollarThenPound = withCurrencySymbol("£")(withCurrencySymbol("$")(baseFormatAmount))
    expect(dollarThenPound(99)).toBe("£$99")
  })
})

// ── Pattern 3 — explicit props (no context) ──────────────────────────────────
// The explicit-props pattern makes components 100% pure and testable without
// React context or a provider. Wire logic at the call site: <MyWidget logic={...} />

describe("Pattern 3: explicit props — testable without any context", () => {
  test("component using explicit logic prop requires no provider", () => {
    // createLogic produces the same logic the registry would hold
    const ukLogic = createUkLogic(ukConfig)

    // Simulates the component logic branch — no React, no render needed
    const formatted = ukLogic.formatAmount(150)
    const isValid = ukLogic.validateAmount(150)

    expect(formatted).toBe("£150 inc. VAT")
    // ukConfig has showDetailsTab: false — validation is gated
    expect(isValid).toBe(false)
  })

  test("swapping logic implementations changes output without touching the component", () => {
    // This is the core value of Pattern 3: the component doesn't change,
    // only the injected logic does.
    const ukLogic = createUkLogic(ukConfig)
    const usLogic = createUsLogic(usConfig)
    const sgLogic = createSgLogic(sgConfig)

    // Same "component" (just the format call), different injected logic
    const display = (logic: typeof ukLogic, amount: number) => logic.formatAmount(amount)

    expect(display(ukLogic, 99)).toBe("£99 inc. VAT")
    expect(display(usLogic, 99)).toBe("$99")
    expect(display(sgLogic, 99)).toBe("SGD 99")
  })
})

// ── Cross-region registry shape validation ───────────────────────────────────
// Validates that every region's registry satisfies the full RegionalRegistry
// contract at runtime. Add your new region here after creating its folder.

describe("cross-region registry shape validation", () => {
  const registries = [
    ["default", defaultRegistry],
    ["uk", ukRegistry],
    ["us", usRegistry],
    ["sg", sgRegistry],
  ] as const

  test.each(registries)("%s registry — config.id is a non-empty string", (_name, registry) => {
    expect(typeof registry.config.id).toBe("string")
    expect(registry.config.id.length).toBeGreaterThan(0)
  })

  test.each(registries)("%s registry — config.locale matches xx-XX format", (_name, registry) => {
    expect(registry.config.locale).toMatch(/^[a-z]{2}-[A-Z]{2}$/)
  })

  test.each(registries)("%s registry — logic.formatAmount(100) returns a string", (_name, registry) => {
    expect(typeof registry.logic.formatAmount(100)).toBe("string")
  })

  test.each(registries)("%s registry — logic.validateAmount(100) returns a boolean", (_name, registry) => {
    expect(typeof registry.logic.validateAmount(100)).toBe("boolean")
  })

  test.each(registries)("%s registry — addons.wrappers is an Array", (_name, registry) => {
    expect(Array.isArray(registry.addons.wrappers)).toBe(true)
  })

  test.each(registries)("%s registry — components.PricingWidget is a function", (_name, registry) => {
    expect(typeof registry.components.PricingWidget).toBe("function")
  })
})

// ── createRegistry() helper tests ────────────────────────────────────────────
// createRegistry(base, overrides) composes a RegionalRegistry from a base and
// a partial override — only specify what changes, inherit everything else.

describe("createRegistry", () => {
  test("inherits base config when no config override", () => {
    const reg = createRegistry(defaultRegistry, {})
    expect(reg.config.id).toBe("default")
    expect(reg.config.currency).toBe("USD")
  })

  test("overrides config when provided", () => {
    const reg = createRegistry(defaultRegistry, { config: ukConfig })
    expect(reg.config.id).toBe("uk")
    expect(reg.config.currency).toBe("GBP")
  })

  test("inherits base logic when no logic override", () => {
    const reg = createRegistry(defaultRegistry, {})
    expect(reg.logic.formatAmount(99)).toBe("99") // baseFormatAmount
  })

  test("overrides logic when provided", () => {
    const reg = createRegistry(defaultRegistry, {
      logic: createUkLogic(ukConfig),
    })
    expect(reg.logic.formatAmount(99)).toBe("£99 inc. VAT")
  })

  test("inherits base components when no components override", () => {
    const reg = createRegistry(defaultRegistry, {})
    expect(reg.components.PricingWidget).toBe(defaultRegistry.components.PricingWidget)
  })

  test("merges components — only specified slots are overridden", () => {
    const MockWidget = (_props: { amount: number }) => null
    const reg = createRegistry(defaultRegistry, {
      components: { PricingWidget: MockWidget },
    })
    expect(reg.components.PricingWidget).toBe(MockWidget)
  })

  test("inherits empty wrappers when no addons override", () => {
    const reg = createRegistry(defaultRegistry, {})
    expect(reg.addons.wrappers).toEqual([])
  })

  test("overrides addons.wrappers when provided", () => {
    const MockWrapper = ({ children }: { children: unknown }) => children
    const reg = createRegistry(defaultRegistry, {
      addons: { wrappers: [MockWrapper as never] },
    })
    expect(reg.addons.wrappers).toHaveLength(1)
    expect(reg.addons.wrappers[0]).toBe(MockWrapper)
  })

  test("SG pattern: only logic override inherits all else from default", () => {
    const sgLogic = createSgLogic(sgConfig)
    const reg = createRegistry(defaultRegistry, {
      config: sgConfig,
      logic: sgLogic,
    })
    expect(reg.config.id).toBe("sg")
    expect(reg.logic.formatAmount(99)).toBe("SGD 99")
    expect(reg.components.PricingWidget).toBe(defaultRegistry.components.PricingWidget)
    expect(reg.addons.wrappers).toEqual([])
  })
})
