"""
Localization Service — Tests.
تست‌های واحد و API برای سرویس بومی‌سازی.
"""
import pytest
from django.test import override_settings

pytestmark = [pytest.mark.django_db]


# ─── Model Tests ─────────────────────────────────────────────────────────


class TestCountryModel:
    def test_create_country(self):
        from apps.core.localization.models import Country
        country = Country.objects.create(
            name='ایران',
            name_en='Iran',
            iso2='IR',
            iso3='IRN',
            phone_code='+98',
            flag_emoji='🇮🇷',
            is_active=True,
        )
        assert 'ایران' in str(country)
        assert 'IR' in str(country)
        assert country.iso2 == 'IR'

    def test_country_unique_iso2(self):
        from apps.core.localization.models import Country
        from django.db import IntegrityError
        Country.objects.create(name='ایران', name_en='Iran', iso2='IR', iso3='IRN', phone_code='+98')
        with pytest.raises(IntegrityError):
            Country.objects.create(name='ایران 2', name_en='Iran 2', iso2='IR', iso3='IR2', phone_code='+98')


class TestLanguageModel:
    def test_create_language(self):
        from apps.core.localization.models import Language
        lang = Language.objects.create(
            code='fa',
            name='فارسی',
            name_en='Persian',
            direction='rtl',
            is_active=True,
        )
        assert str(lang) == 'فارسی (fa)'
        assert lang.direction == 'rtl'


class TestCurrencyModel:
    def test_create_currency(self):
        from apps.core.localization.models import Currency
        cur = Currency.objects.create(
            code='IRR',
            name='ریال ایران',
            name_en='Iranian Rial',
            symbol='﷼',
            decimal_places=0,
        )
        assert str(cur) == 'ریال ایران (IRR)'
        assert cur.decimal_places == 0


class TestProvinceCity:
    def test_province_city_hierarchy(self):
        from apps.core.localization.models import Country, Province, City
        country = Country.objects.create(name='ایران', name_en='Iran', iso2='IR', iso3='IRN', phone_code='+98')
        province = Province.objects.create(name='تهران', name_en='Tehran', country=country)
        city = City.objects.create(name='تهران', name_en='Tehran', province=province)
        assert city.province.country == country
        assert str(province) == 'تهران'


class TestCalendarSystem:
    def test_create_calendar(self):
        from apps.core.localization.models import Country, CalendarSystem
        country = Country.objects.create(name='ایران', name_en='Iran', iso2='IR', iso3='IRN', phone_code='+98')
        cal = CalendarSystem.objects.create(
            code='jalali',
            name='شمسی',
            name_en='Jalali',
            country=country,
            is_default=True,
        )
        assert str(cal) == 'شمسی (jalali)'


# ─── Service Tests ───────────────────────────────────────────────────────


class TestLocalizationService:
    def test_format_number_persian(self):
        from apps.core.localization.services import LocalizationService
        from apps.core.localization.models import Language
        lang = Language.objects.create(code='fa', name='فارسی', name_en='Persian', number_format='persian', is_active=True)
        result = LocalizationService.format_number(1234567.89, language=lang)
        assert '۱' in result

    def test_format_number_latin(self):
        from apps.core.localization.services import LocalizationService
        from apps.core.localization.models import Language
        lang = Language.objects.create(code='en', name='English', name_en='English', number_format='latin', is_active=True)
        result = LocalizationService.format_number(1234567.89, language=lang)
        assert '1' in result

    def test_format_currency(self):
        from apps.core.localization.services import LocalizationService
        from apps.core.localization.models import Currency
        cur = Currency.objects.create(code='IRR', name='ریال', name_en='Rial', symbol='ریال', decimal_places=0, position='after')
        result = LocalizationService.format_currency(50000, currency=cur)
        assert 'ریال' in result

    def test_get_active_locale_defaults(self):
        from apps.core.localization.services import LocalizationService
        from apps.core.localization.models import Language, Currency, Timezone, CalendarSystem, Country
        # Create default records
        country = Country.objects.create(name='ایران', name_en='Iran', iso2='IR', iso3='IRN', phone_code='+98', is_active=True)
        Language.objects.create(code='fa', name='فارسی', name_en='Persian', is_active=True)
        Currency.objects.create(code='IRR', name='ریال', name_en='Rial', symbol='﷼')
        Timezone.objects.create(identifier='Asia/Tehran', utc_offset='+03:30', country=country)
        CalendarSystem.objects.create(code='jalali', name='شمسی', name_en='Jalali', country=country, is_default=True)

        locale = LocalizationService.get_active_locale(user=None, tenant=None)
        assert locale['language'] is not None
        assert locale['language'].code == 'fa'
        assert locale['timezone'].identifier == 'Asia/Tehran'
        assert locale['calendar'].code == 'jalali'


# ─── API Tests ───────────────────────────────────────────────────────────


class TestLocalizationAPI:
    def test_countries_list(self, api_client):
        from apps.core.localization.models import Country
        Country.objects.create(name='ایران', name_en='Iran', iso2='IR', iso3='IRN', phone_code='+98', is_active=True)
        response = api_client.get('/api/v1/localization/countries/')
        assert response.status_code == 200

    def test_languages_list(self, api_client):
        from apps.core.localization.models import Language
        Language.objects.create(code='fa', name='فارسی', name_en='Persian', is_active=True)
        response = api_client.get('/api/v1/localization/languages/')
        assert response.status_code == 200

    def test_currencies_list(self, api_client):
        from apps.core.localization.models import Currency
        Currency.objects.create(code='IRR', name='ریال ایران', name_en='Iranian Rial', symbol='﷼')
        response = api_client.get('/api/v1/localization/currencies/')
        assert response.status_code == 200

    def test_active_locale_unauthenticated(self, api_client):
        response = api_client.get('/api/v1/localization/active-locale/')
        assert response.status_code == 200
        data = response.json()
        assert 'data' in data
        assert 'language' in data['data']

    def test_countries_inactive_filtered(self, api_client):
        from apps.core.localization.models import Country
        Country.objects.create(name='فعال', name_en='Active', iso2='AC', iso3='ACT', phone_code='+1', is_active=True)
        Country.objects.create(name='غیرفعال', name_en='Inactive', iso2='IN', iso3='INA', phone_code='+2', is_active=False)
        response = api_client.get('/api/v1/localization/countries/')
        assert response.status_code == 200
