import { describe, expect, it } from 'vitest'
import { getCanonicalOrigin } from '@platform-modules/seo/canonical'
import { isIndexable, robotsValue } from '@platform-modules/seo/gate'
import { buildHrefLangs } from '@platform-modules/seo/hreflang'
import { serializeJsonLd } from '@platform-modules/seo/jsonld'
import { renderSitemapIndex, renderUrlSet } from '@platform-modules/seo/sitemap'

const LS = '\u2028'
const PS = '\u2029'

describe('seo consumer fixture (Gate 3)', () => {
  it('neutralizes JSON-LD escaping union regression payload', () => {
    const out = serializeJsonLd({
      trap: `</script><!--&${LS}${PS}`,
    })
    expect(out).not.toContain('<')
    expect(out).not.toContain(LS)
    expect(out).not.toContain(PS)
  })

  it('renders sitemap index and urlset as valid XML', () => {
    const index = renderSitemapIndex([{ loc: 'https://example.com/sitemap-1.xml' }])
    expect(index).toMatch(/^<\?xml/)
    expect(index).toContain('<sitemapindex')

    const urlset = renderUrlSet([{ loc: 'https://example.com/page' }])
    expect(urlset).toContain('<urlset')
    expect(urlset).toContain('<loc>https://example.com/page</loc>')
  })

  it('maps isIndexable to robotsValue', () => {
    const ok = isIndexable({ indexingEnabled: true }, { published: true })
    expect(robotsValue(ok)).toBe('index,follow')
    const no = isIndexable({ indexingEnabled: true }, { published: false })
    expect(robotsValue(no)).toBe('noindex,nofollow')
  })

  it('buildHrefLangs emits x-default and per-locale alternates', () => {
    const links = buildHrefLangs(['en', 'he'], 'en', (l) => `https://shop.test/${l}`)
    expect(links.some((l) => l.hreflang === 'x-default')).toBe(true)
    expect(links.some((l) => l.hreflang === 'en')).toBe(true)
    expect(links.some((l) => l.hreflang === 'he-IL')).toBe(true)
  })

  it('getCanonicalOrigin prefers custom domain over subdomain', () => {
    expect(
      getCanonicalOrigin({
        customDomain: 'custom.example.com',
        subdomain: 'tenant',
        baseDomain: 'platform.test',
      }),
    ).toBe('https://custom.example.com')
  })
})
