from decimal import Decimal

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

from accounts.models import TransporterProfile, UserRole, Vehicle

User = get_user_model()


class VehicleRegistrationUniquenessApiTests(APITestCase):
    def setUp(self):
        self.owner = User.objects.create_user(
            'vehicle-owner@test.com',
            email='vehicle-owner@test.com',
            password='secret',
        )
        UserRole.objects.create(user=self.owner, role=UserRole.Role.TRANSPORTER, phone='', language='en')
        TransporterProfile.objects.create(
            user=self.owner,
            account_type=TransporterProfile.AccountType.FLEET_OWNER,
            company_name='Fleet Co',
            local=True,
            country_to_country=False,
        )
        Vehicle.objects.create(
            owner=self.owner,
            vehicle_type='Truck',
            registration_number='abcssd',
            load_capacity=Decimal('10000.00'),
        )
        token, _ = Token.objects.get_or_create(user=self.owner)
        self.client = APIClient()
        self.client.credentials(HTTP_AUTHORIZATION=f'Bearer {token.key}')

    def test_create_rejects_duplicate_registration_per_owner(self):
        response = self.client.post(
            '/api/transporter/vehicles/',
            {
                'vehicle_type': 'Truck',
                'registration_number': 'abcssd',
                'load_capacity': '12000.00',
            },
            format='json',
        )
        self.assertEqual(response.status_code, 400, response.content)
        body = response.json()
        self.assertEqual(body['message'], 'Validation failed.')
        self.assertIn('registration_number', body['error'])
        self.assertEqual(Vehicle.objects.filter(owner=self.owner).count(), 1)

    def test_other_owner_can_reuse_registration_number(self):
        other = User.objects.create_user(
            'other-owner@test.com',
            email='other-owner@test.com',
            password='secret',
        )
        UserRole.objects.create(user=other, role=UserRole.Role.TRANSPORTER, phone='', language='en')
        TransporterProfile.objects.create(
            user=other,
            account_type=TransporterProfile.AccountType.DRIVER,
            local=True,
            country_to_country=False,
        )
        token, _ = Token.objects.get_or_create(user=other)
        client = APIClient()
        client.credentials(HTTP_AUTHORIZATION=f'Bearer {token.key}')

        response = client.post(
            '/api/transporter/vehicles/',
            {
                'vehicle_type': 'Van',
                'registration_number': 'abcssd',
                'load_capacity': '5000.00',
            },
            format='json',
        )
        self.assertEqual(response.status_code, 201, response.content)
