from django.db import IntegrityError, transaction
from django.test import TestCase

from shop.models import HULL, Shop, ShopSource
from shop.tests._corptools import make_corp_owner, make_owner_character


class ShopSourceModelTests(TestCase):
    def test_source_references_character_audit_and_location_id(self):
        user, audit = make_owner_character()
        shop = Shop.objects.create(slug="s", name="S", created_by=user)
        src = ShopSource.objects.create(
            shop=shop, section=HULL, character_audit=audit, location_id=60003760
        )
        self.assertEqual(src.character_audit_id, audit.pk)
        self.assertEqual(src.location_id, 60003760)
        self.assertIsNone(src.container_item_id)
        self.assertEqual(src.owner_display, audit.character.character_name)

    def test_corp_source_stores_corporation_audit_and_negative_location(self):
        user, corp_audit = make_corp_owner()
        shop = Shop.objects.create(slug="c", name="C", created_by=user)
        src = ShopSource.objects.create(
            shop=shop,
            section=HULL,
            corporation_audit=corp_audit,
            location_id=-600037601,
        )
        self.assertIsNone(src.character_audit_id)
        self.assertEqual(src.corporation_audit_id, corp_audit.pk)
        self.assertEqual(src.location_id, -600037601)
        self.assertEqual(src.owner_display, corp_audit.corporation.corporation_name)

    def test_cannot_set_both_owners(self):
        user, audit = make_owner_character()
        _, corp_audit = make_corp_owner(username="co2", char_id=1002, corp_id=2002)
        shop = Shop.objects.create(slug="b", name="B", created_by=user)
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                ShopSource.objects.create(
                    shop=shop,
                    section=HULL,
                    character_audit=audit,
                    corporation_audit=corp_audit,
                    location_id=1,
                )

    def test_cannot_set_neither_owner(self):
        user, _ = make_owner_character()
        shop = Shop.objects.create(slug="n", name="N", created_by=user)
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                ShopSource.objects.create(shop=shop, section=HULL, location_id=1)
