import { describe, it, expect } from 'vitest';
import { getStateInfoClient } from '@/lib/getStateInfoClient';
import {
    buildCanonicalUrl,
    buildCanonicalPath,
    buildMainCanonicalUrl,
    normalizeHost,
} from '@/lib/getCanonicalUrl';

function setLocation(loc) {
    Object.defineProperty(window, 'location', { value: loc, writable: true, configurable: true });
}

describe('getStateInfoClient (window)', () => {
    it('subdomain شناخته‌شده → شهر و استان', () => {
        setLocation({ host: 'arak-nobat.ir', href: 'https://arak-nobat.ir/' });
        const { matchedCity, matchedState, host } = getStateInfoClient();
        expect(matchedCity?.name).toBe('اراک');
        expect(matchedState?.name).toBe('مرکزی');
        expect(host).toBe('arak-nobat.ir');
    });

    it('host ناشناخته → بدون تطبیق', () => {
        setLocation({ host: 'zzz.ir', href: 'https://zzz.ir/' });
        expect(getStateInfoClient().matchedCity).toBeUndefined();
    });
});

describe('buildCanonicalUrl (self-canonical per-host)', () => {
    it('دامنه‌ی شهری → self-canonical روی همان دامنه', () => {
        expect(buildCanonicalUrl('arak-nobat.ir', '/doctors')).toBe('https://arak-nobat.ir/doctors');
    });

    it('دامنه‌ی اصلی → self-canonical روی دامنه‌ی اصلی', () => {
        expect(buildCanonicalUrl('nobat724.com', '/doctors')).toBe('https://nobat724.com/doctors');
    });

    it('www و حروف بزرگ نرمال می‌شوند', () => {
        expect(buildCanonicalUrl('WWW.Nobat724.com', '/x')).toBe('https://nobat724.com/x');
    });

    it('هاست dev با پورت → http و حفظ پورت', () => {
        expect(buildCanonicalUrl('yazd-nobat.localhost:3000', '/doctors')).toBe(
            'http://yazd-nobat.localhost:3000/doctors'
        );
    });

    it('query string و trailing slash حذف می‌شوند', () => {
        expect(buildCanonicalUrl('arak-nobat.ir', '/doctors/?specialty=قلب')).toBe(
            'https://arak-nobat.ir/doctors'
        );
    });

    it('ریشه دست‌نخورده می‌ماند', () => {
        expect(buildCanonicalUrl('arak-nobat.ir', '/')).toBe('https://arak-nobat.ir/');
        expect(buildCanonicalPath('/')).toBe('/');
    });

    it('هاست خالی → دامنه‌ی پیش‌فرض', () => {
        expect(normalizeHost('')).toBe('nobat724.com');
        expect(buildCanonicalUrl(null, '/x')).toBe('https://nobat724.com/x');
    });
});

describe('buildMainCanonicalUrl (canonical متادیتا → دامنه‌ی اصلی)', () => {
    it('هر مسیری → همان مسیر روی nobat724.com', () => {
        expect(buildMainCanonicalUrl('/doctors')).toBe('https://nobat724.com/doctors');
        expect(buildMainCanonicalUrl('/doctor/abc-123')).toBe('https://nobat724.com/doctor/abc-123');
    });

    it('ریشه → با trailing slash', () => {
        expect(buildMainCanonicalUrl('/')).toBe('https://nobat724.com/');
    });

    it('query و trailing slash حذف می‌شوند', () => {
        expect(buildMainCanonicalUrl('/doctors/?specialty=قلب')).toBe('https://nobat724.com/doctors');
    });
});
