"""ShopForm tests."""

from django.contrib.auth.models import User
from django.test import TestCase

from allianceauth.eveonline.models import EveCorporationInfo
from allianceauth.tests.auth_utils import AuthUtils

from shop.forms import ShopForm
from shop.models import Shop


class ShopFormTests(TestCase):
    def setUp(self):
        self.user = AuthUtils.create_user("creator")
        AuthUtils.add_main_character_2(self.user, "Main", 1001, corp_id=2001, disconnect_signals=True)

    def test_personal_shop_valid_and_sets_creator(self):
        form = ShopForm(
            {"name": "P", "slug": "p", "shop_type": "personal", "is_published": False},
            user=self.user,
        )
        self.assertTrue(form.is_valid(), form.errors)
        shop = form.save()
        self.assertEqual(shop.created_by, self.user)
        self.assertIsNone(shop.corporation)

    def test_description_saved(self):
        form = ShopForm(
            {"name": "P", "slug": "p", "shop_type": "personal",
             "is_published": False, "description": "**hi**"},
            user=self.user,
        )
        self.assertTrue(form.is_valid(), form.errors)
        shop = form.save()
        self.assertEqual(shop.description, "**hi**")

    def test_invalid_slug_rejected(self):
        form = ShopForm(
            {"name": "P", "slug": "Bad Slug", "shop_type": "personal", "is_published": False},
            user=self.user,
        )
        self.assertFalse(form.is_valid())
        self.assertIn("slug", form.errors)

    def test_corp_shop_requires_permission(self):
        form = ShopForm(
            {"name": "C", "slug": "c", "shop_type": "corporation", "is_published": False},
            user=self.user,  # has no manage_corporation_shops perm
        )
        self.assertFalse(form.is_valid())
        self.assertIn("shop_type", form.errors)

    def test_corp_shop_sets_corporation(self):
        EveCorporationInfo.objects.create(
            corporation_id=2001, corporation_name="Corp",
            corporation_ticker="CORP", member_count=1,
        )
        AuthUtils.add_permission_to_user_by_name("shop.manage_corporation_shops", self.user)
        user = User.objects.get(pk=self.user.pk)
        form = ShopForm(
            {"name": "C", "slug": "c", "shop_type": "corporation", "is_published": False},
            user=user,
        )
        self.assertTrue(form.is_valid(), form.errors)
        shop = form.save()
        self.assertEqual(shop.shop_type, Shop.ShopType.CORPORATION)
        self.assertEqual(shop.corporation.corporation_id, 2001)
