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, TransporterDriverLink, TransporterProfile, UserRole
from core.models import Bid, Shipment, Trip
from core.trip_cancel import cancel_trip

User = get_user_model()


class CancelledTripListBucketsTests(TestCase):
    def setUp(self):
        self.shipper = User.objects.create_user(
            'cancel-bucket-ship@test.com',
            email='cancel-bucket-ship@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.owner = User.objects.create_user(
            'cancel-bucket-owner@test.com',
            email='cancel-bucket-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,
            local=True,
            country_to_country=False,
            documents_verified=True,
        )

        self.driver = User.objects.create_user(
            'cancel-bucket-drv@test.com',
            email='cancel-bucket-drv@test.com',
            password='secret',
        )
        UserRole.objects.create(user=self.driver, role=UserRole.Role.TRANSPORTER, phone='', language='en')
        TransporterProfile.objects.create(
            user=self.driver,
            account_type=TransporterProfile.AccountType.TRANSPORTER_DRIVER,
            local=True,
            country_to_country=False,
            documents_verified=True,
        )
        TransporterDriverLink.objects.create(transporter=self.owner, driver=self.driver, is_active=True)

        token, _ = Token.objects.get_or_create(user=self.owner)
        self.client = APIClient()
        self.client.credentials(HTTP_AUTHORIZATION=f'Bearer {token.key}')

        dtoken, _ = Token.objects.get_or_create(user=self.driver)
        self.driver_client = APIClient()
        self.driver_client.credentials(HTTP_AUTHORIZATION=f'Bearer {dtoken.key}')

    def _trip(self, *, status=Trip.Status.ASSIGNED, with_driver=True):
        shipment = Shipment.objects.create(
            shipper=self.shipper,
            pickup_address='A',
            delivery_address='B',
            cargo_type='General',
            weight='1 ton',
            vehicle_type_required='Flatbed',
            local=True,
            country_to_country=False,
            status=Shipment.Status.ASSIGNED,
        )
        bid = Bid.objects.create(
            shipment=shipment,
            transporter=self.owner,
            amount=Decimal('100.00'),
            status=Bid.Status.ACCEPTED,
        )
        return Trip.objects.create(
            shipment=shipment,
            accepted_bid=bid,
            transporter=self.owner,
            assigned_driver=self.driver if with_driver else None,
            status=status,
            agreed_price=Decimal('100.00'),
        )

    def test_trips_my_excludes_cancelled_completed_includes(self):
        live = self._trip(status=Trip.Status.ASSIGNED, with_driver=False)
        cancelled = self._trip(status=Trip.Status.ASSIGNED, with_driver=False)
        cancel_trip(
            trip=cancelled,
            user=self.shipper,
            reason_code='NO_LONGER_NEEDED',
            reason_text='',
        )

        my_res = self.client.get('/api/transporter/trips/my/')
        self.assertEqual(my_res.status_code, 200, my_res.content)
        my_ids = [t['id'] for t in my_res.json()['data']]
        self.assertIn(live.id, my_ids)
        self.assertNotIn(cancelled.id, my_ids)

        completed = self.client.get('/api/transporter/trips/completed/')
        self.assertEqual(completed.status_code, 200, completed.content)
        completed_ids = [t['id'] for t in completed.json()['data']['trips']]
        self.assertIn(cancelled.id, completed_ids)
        self.assertNotIn(live.id, completed_ids)

        assigned = self.client.get('/api/transporter/trips/assigned/')
        self.assertEqual(assigned.status_code, 200)
        assigned_ids = [t['id'] for t in assigned.json()['data']]
        self.assertNotIn(cancelled.id, assigned_ids)

        active = self.client.get('/api/transporter/trips/active/')
        self.assertEqual(active.status_code, 200)
        active_ids = [t['id'] for t in active.json()['data']]
        self.assertNotIn(cancelled.id, active_ids)

    def test_fleet_driver_completed_includes_cancelled(self):
        trip = self._trip(status=Trip.Status.ASSIGNED, with_driver=True)
        cancel_trip(
            trip=trip,
            user=self.shipper,
            reason_code='WRONG_DETAILS',
            reason_text='',
        )

        completed = self.driver_client.get('/api/transporter/driver/trips/completed/')
        self.assertEqual(completed.status_code, 200, completed.content)
        ids = [t['id'] for t in completed.json()['data']]
        self.assertIn(trip.id, ids)

        active = self.driver_client.get('/api/transporter/driver/trips/active/')
        self.assertEqual(active.status_code, 200)
        self.assertNotIn(trip.id, [t['id'] for t in active.json()['data']])

        assigned = self.driver_client.get('/api/transporter/driver/trips/assigned/')
        self.assertEqual(assigned.status_code, 200)
        self.assertNotIn(trip.id, [t['id'] for t in assigned.json()['data']])
