from decimal import Decimal

from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

from accounts.models import ShipperProfile, TransporterProfile, UserRole
from billing.models import Invoice
from billing.services import ensure_invoice_for_completed_trip
from core.models import Bid, CountryBoundary, CountryVatRate, FreightRoute, Shipment, Trip, Zone
from core.vat import apply_vat, vat_for_country

User = get_user_model()

AE_SQUARE = {
    'type': 'Polygon',
    'coordinates': [[
        [54.0, 24.0],
        [56.0, 24.0],
        [56.0, 26.0],
        [54.0, 26.0],
        [54.0, 24.0],
    ]],
}

SA_SQUARE = {
    'type': 'Polygon',
    'coordinates': [[
        [45.0, 24.0],
        [50.0, 24.0],
        [50.0, 27.0],
        [45.0, 27.0],
        [45.0, 24.0],
    ]],
}

PK_SQUARE = {
    'type': 'Polygon',
    'coordinates': [[
        [66.0, 24.0],
        [70.0, 24.0],
        [70.0, 30.0],
        [66.0, 30.0],
        [66.0, 24.0],
    ]],
}

AF_SQUARE = {
    'type': 'Polygon',
    'coordinates': [[
        [66.0, 32.0],
        [70.0, 32.0],
        [70.0, 38.0],
        [66.0, 38.0],
        [66.0, 32.0],
    ]],
}


class VatHelperTests(TestCase):
    def test_apply_vat_adds_fixed_amount(self):
        result = apply_vat(Decimal('1000.00'), Decimal('300.00'))
        self.assertEqual(result['vat_amount'], Decimal('300.00'))
        self.assertEqual(result['total_incl_vat'], Decimal('1300.00'))

    def test_missing_country_rate_is_zero(self):
        self.assertEqual(vat_for_country('ZZ'), Decimal('0.00'))
        self.assertEqual(vat_for_country('AF'), Decimal('0.00'))

    def test_inactive_rate_is_zero(self):
        CountryVatRate.objects.update_or_create(
            country_code='AE',
            defaults={'vat_amount': Decimal('300.00'), 'is_active': False},
        )
        self.assertEqual(vat_for_country('AE'), Decimal('0.00'))


class C2CEstimateVatTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('vat-ship@test.com', email='vat-ship@test.com', password='secret')
        UserRole.objects.create(user=self.user, role=UserRole.Role.SHIPPER, phone='', language='en')
        ShipperProfile.objects.create(user=self.user, account_type=ShipperProfile.AccountType.INDIVIDUAL)
        token, _ = Token.objects.get_or_create(user=self.user)
        self.client = APIClient()
        self.client.credentials(HTTP_AUTHORIZATION=f'Bearer {token.key}')
        self.url = '/api/shipper/shipments/estimate-price/'

        CountryBoundary.objects.create(country_code='AE', country_name='UAE', geojson=AE_SQUARE)
        CountryBoundary.objects.create(country_code='SA', country_name='Saudi Arabia', geojson=SA_SQUARE)
        CountryBoundary.objects.create(country_code='PK', country_name='Pakistan', geojson=PK_SQUARE)
        CountryBoundary.objects.create(country_code='AF', country_name='Afghanistan', geojson=AF_SQUARE)

        CountryVatRate.objects.update_or_create(
            country_code='AE',
            defaults={'vat_amount': Decimal('300.00'), 'is_active': True},
        )
        FreightRoute.objects.create(
            origin_country_code='AE',
            destination_country_code='SA',
            min_freight=Decimal('1000.00'),
            currency='AED',
        )
        FreightRoute.objects.create(
            origin_country_code='PK',
            destination_country_code='AF',
            min_freight=Decimal('1500.00'),
            currency='PKR',
        )

        self.ae_to_sa = {
            'pickup_lat': '25.0000000',
            'pickup_lon': '55.0000000',
            'delivery_lat': '25.5000000',
            'delivery_lon': '47.0000000',
        }
        self.pk_to_af = {
            'pickup_lat': '25.0000000',
            'pickup_lon': '67.0000000',
            'delivery_lat': '34.0000000',
            'delivery_lon': '67.0000000',
        }
        self.ae_local = {
            'pickup_lat': '25.0000000',
            'pickup_lon': '55.0000000',
            'delivery_lat': '25.5000000',
            'delivery_lon': '55.5000000',
        }

    def test_c2c_estimate_applies_fixed_pickup_vat(self):
        response = self.client.post(self.url, self.ae_to_sa, format='json')
        self.assertEqual(response.status_code, 200, response.content)
        data = response.json()['data']
        self.assertEqual(data['suggested_price'], '1000.00')
        self.assertEqual(data['vat_country_code'], 'AE')
        self.assertEqual(data['vat_amount'], '300.00')
        self.assertEqual(data['total_incl_vat'], '1300.00')
        self.assertNotIn('vat_rate_percent', data)

    def test_local_estimate_has_zero_vat(self):
        Zone.objects.create(country_code='AE', radius_km=Decimal('50'), rate_per_km=Decimal('2.00'))
        response = self.client.post(self.url, self.ae_local, format='json')
        self.assertEqual(response.status_code, 200, response.content)
        data = response.json()['data']
        self.assertIsNotNone(data['suggested_price'])
        self.assertEqual(data['vat_amount'], '0.00')
        self.assertEqual(data['total_incl_vat'], data['suggested_price'])

    def test_c2c_missing_country_rate_is_zero(self):
        CountryVatRate.objects.filter(country_code='PK').delete()
        response = self.client.post(self.url, self.pk_to_af, format='json')
        self.assertEqual(response.status_code, 200, response.content)
        data = response.json()['data']
        self.assertEqual(data['suggested_price'], '1500.00')
        self.assertEqual(data['vat_country_code'], 'PK')
        self.assertEqual(data['vat_amount'], '0.00')
        self.assertEqual(data['total_incl_vat'], '1500.00')


class InvoiceVatTests(TestCase):
    def setUp(self):
        self.shipper = User.objects.create_user('vat-inv-s@test.com', email='vat-inv-s@test.com', password='secret')
        UserRole.objects.create(user=self.shipper, role=UserRole.Role.SHIPPER, phone='', language='en')
        ShipperProfile.objects.create(user=self.shipper, account_type=ShipperProfile.AccountType.INDIVIDUAL)

        self.transporter = User.objects.create_user('vat-inv-t@test.com', email='vat-inv-t@test.com', password='secret')
        UserRole.objects.create(user=self.transporter, role=UserRole.Role.TRANSPORTER, phone='1', language='en')
        TransporterProfile.objects.create(
            user=self.transporter,
            account_type=TransporterProfile.AccountType.DRIVER,
            local=False,
            country_to_country=True,
            documents_verified=True,
        )

        CountryVatRate.objects.update_or_create(
            country_code='AE',
            defaults={'vat_amount': Decimal('450.00'), 'is_active': True},
        )

    def _completed_trip(self, *, c2c: bool, pickup_country='AE', delivery_country='SA', amount='1000.00'):
        shipment = Shipment.objects.create(
            shipper=self.shipper,
            pickup_address='A',
            delivery_address='B',
            cargo_type='General',
            weight='1 ton',
            vehicle_type_required='Flatbed',
            pickup_country_code=pickup_country,
            delivery_country_code=delivery_country,
            local=not c2c,
            country_to_country=c2c,
            status=Shipment.Status.DELIVERED,
        )
        bid = Bid.objects.create(
            shipment=shipment,
            transporter=self.transporter,
            amount=Decimal(amount),
            status=Bid.Status.ACCEPTED,
        )
        trip = Trip.objects.create(
            shipment=shipment,
            accepted_bid=bid,
            transporter=self.transporter,
            status=Trip.Status.COMPLETED,
        )
        return trip

    def test_c2c_invoice_applies_fixed_pickup_vat(self):
        trip = self._completed_trip(c2c=True, pickup_country='AE', delivery_country='SA', amount='1000.00')
        invoice = ensure_invoice_for_completed_trip(trip=trip)
        self.assertEqual(invoice.subtotal, Decimal('1000.00'))
        self.assertEqual(invoice.vat_country_code, 'AE')
        self.assertEqual(invoice.tax, Decimal('450.00'))
        self.assertEqual(invoice.total, Decimal('1450.00'))
        line_amount = Decimal(invoice.line_items[0]['amount'])
        self.assertEqual(line_amount, Decimal('1000.00'))

    def test_local_invoice_tax_stays_zero(self):
        trip = self._completed_trip(
            c2c=False,
            pickup_country='AE',
            delivery_country='AE',
            amount='120.00',
        )
        invoice = ensure_invoice_for_completed_trip(trip=trip)
        self.assertEqual(invoice.subtotal, Decimal('120.00'))
        self.assertEqual(invoice.tax, Decimal('0.00'))
        self.assertEqual(invoice.total, Decimal('120.00'))
        self.assertEqual(Invoice.objects.filter(trip=trip).count(), 1)
