from decimal import Decimal

from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction

from core.models import Listing, Profile


class Command(BaseCommand):
    help = "Seed sample Malawi-focused users, profiles, and listings into the system."

    @transaction.atomic
    def handle(self, *args, **options):
        self.stdout.write("Preparing Malawi-focused demo data…")
        call_command("seed_categories", stdout=self.stdout, stderr=self.stderr)

        User = get_user_model()

        users_data = [
            {
                "username": "chifundo",
                "email": "chifundo@example.mw",
                "first_name": "Chifundo",
                "last_name": "Banda",
                "password": "demo12345",
                "profile": {
                    "phone": "+265991234567",
                    "whatsapp": "+265991234567",
                    "bio": "Malawi-based property owner focused on family homes in Lilongwe.",
                    "is_lister": True,
                    "is_discoverer": True,
                    "account_type": Profile.INDIVIDUAL,
                    "verification_status": Profile.VERIFIED,
                    "preferred_currency": "MWK",
                    "preferred_language": "en",
                },
            },
            {
                "username": "tiwonge",
                "email": "tiwonge@example.mw",
                "first_name": "Tiwonge",
                "last_name": "Nkhoma",
                "password": "demo12345",
                "profile": {
                    "phone": "+265888123456",
                    "whatsapp": "+265888123456",
                    "bio": "Local tour host and hospitality business owner in Salima.",
                    "is_lister": True,
                    "is_discoverer": True,
                    "account_type": Profile.BUSINESS,
                    "business_name": "Nkhoma Hospitality",
                    "business_registration_number": "REG-1001",
                    "business_address": "Old Town, Salima",
                    "verification_status": Profile.VERIFIED,
                    "preferred_currency": "MWK",
                    "preferred_language": "ny",
                },
            },
            {
                "username": "martha",
                "email": "martha@example.mw",
                "first_name": "Martha",
                "last_name": "Phiri",
                "password": "demo12345",
                "profile": {
                    "phone": "+265997111222",
                    "whatsapp": "+265997111222",
                    "bio": "Young professional looking for comfortable rentals near the city.",
                    "is_lister": False,
                    "is_discoverer": True,
                    "account_type": Profile.INDIVIDUAL,
                    "verification_status": Profile.VERIFIED,
                    "preferred_currency": "MWK",
                    "preferred_language": "en",
                },
            },
        ]

        created_users = 0
        for user_data in users_data:
            user, created = User.objects.get_or_create(
                username=user_data["username"],
                defaults={
                    "email": user_data["email"],
                    "first_name": user_data["first_name"],
                    "last_name": user_data["last_name"],
                },
            )
            if created:
                user.set_password(user_data["password"])
                user.save()
                created_users += 1

            profile_defaults = user_data["profile"].copy()
            profile_defaults.pop("phone", None)
            profile_defaults.pop("whatsapp", None)
            profile_defaults.pop("bio", None)
            profile_defaults.pop("is_lister", None)
            profile_defaults.pop("is_discoverer", None)
            profile_defaults.pop("account_type", None)
            profile_defaults.pop("verification_status", None)
            profile_defaults.pop("preferred_currency", None)
            profile_defaults.pop("preferred_language", None)

            profile, _ = Profile.objects.update_or_create(
                user=user,
                defaults={
                    "phone": user_data["profile"].get("phone", ""),
                    "whatsapp": user_data["profile"].get("whatsapp", ""),
                    "bio": user_data["profile"].get("bio", ""),
                    "is_lister": user_data["profile"].get("is_lister", False),
                    "is_discoverer": user_data["profile"].get("is_discoverer", True),
                    "account_type": user_data["profile"].get("account_type", ""),
                    "verification_status": user_data["profile"].get("verification_status", Profile.UNVERIFIED),
                    "preferred_currency": user_data["profile"].get("preferred_currency", "MWK"),
                    "preferred_language": user_data["profile"].get("preferred_language", "en"),
                    **profile_defaults,
                },
            )
            if profile_defaults:
                profile.save()

        listings_data = [
            {
                "slug": "spacious-3-bedroom-house-area-47",
                "title": "Spacious 3-bedroom house in Area 47",
                "category_slug": "property-house",
                "description": "A comfortable family house near the Bingu National Stadium with secure parking, solar backup, and easy access to Lilongwe city centre.",
                "purpose": Listing.PURPOSE_RENT,
                "address": "Area 47, Lilongwe, Malawi",
                "latitude": Decimal("-13.9626"),
                "longitude": Decimal("33.7741"),
                "price": Decimal("450000"),
                "price_period": Listing.PRICE_PERIOD_MONTHLY,
                "currency": "MWK",
                "contact_phone": "+265991234567",
                "contact_whatsapp": "+265991234567",
                "status": Listing.STATUS_ACTIVE,
                "is_verified_listing": True,
                "is_featured": True,
                "attributes": {"bedrooms": 3, "bathrooms": 2, "furnished": True, "amenities": ["Water", "Electricity", "WiFi", "Parking"]},
                "lister_username": "chifundo",
            },
            {
                "slug": "modern-apartment-in-kamuzu-central",
                "title": "Modern apartment near Kamuzu Central Hospital",
                "category_slug": "property-apartment",
                "description": "A tidy two-bedroom apartment suited for professionals and students, with close access to the hospital and nearby shops.",
                "purpose": Listing.PURPOSE_RENT,
                "address": "Area 12, Lilongwe, Malawi",
                "latitude": Decimal("-13.9574"),
                "longitude": Decimal("33.7881"),
                "price": Decimal("350000"),
                "price_period": Listing.PRICE_PERIOD_MONTHLY,
                "currency": "MWK",
                "contact_phone": "+265888123456",
                "contact_whatsapp": "+265888123456",
                "status": Listing.STATUS_ACTIVE,
                "is_verified_listing": True,
                "attributes": {"bedrooms": 2, "bathrooms": 2, "furnished": False, "amenities": ["Water", "Electricity", "WiFi"]},
                "lister_username": "tiwonge",
            },
            {
                "slug": "lake-view-lodge-in-salima",
                "title": "Lake view lodge in Salima",
                "category_slug": "places-hotel-and-lodge",
                "description": "A welcoming lodge with clean rooms, lake views, and easy access to the beach for weekend visitors and local travelers.",
                "purpose": Listing.PURPOSE_SERVICE,
                "address": "Mbenji Beach Road, Salima, Malawi",
                "latitude": Decimal("-13.7833"),
                "longitude": Decimal("34.5833"),
                "price": Decimal("95000"),
                "price_period": Listing.PRICE_PERIOD_NIGHTLY,
                "currency": "MWK",
                "contact_phone": "+265888123456",
                "contact_whatsapp": "+265888123456",
                "status": Listing.STATUS_ACTIVE,
                "is_verified_listing": True,
                "attributes": {"room_types_rates": "Standard and Deluxe rooms", "amenities": ["Pool", "Breakfast", "WiFi", "Parking"]},
                "lister_username": "tiwonge",
            },
            {
                "slug": "organic-farm-in-mzuzu",
                "title": "Organic farm with irrigation near Mzuzu",
                "category_slug": "property-farm",
                "description": "An arable farm with reliable water access, ideal for maize, vegetables, and small-scale agribusiness.",
                "purpose": Listing.PURPOSE_SALE,
                "address": "Lunyangwa, Mzuzu, Malawi",
                "latitude": Decimal("-11.4584"),
                "longitude": Decimal("34.0187"),
                "price": Decimal("9500000"),
                "price_period": Listing.PRICE_PERIOD_ONE_TIME,
                "currency": "MWK",
                "contact_phone": "+265991234567",
                "contact_whatsapp": "+265991234567",
                "status": Listing.STATUS_ACTIVE,
                "is_verified_listing": True,
                "attributes": {"size": "25 acres", "soil_type_or_water_source": "Irrigation and borehole"},
                "lister_username": "chifundo",
            },
        ]

        created_listings = 0
        for listing_data in listings_data:
            lister = User.objects.get(username=listing_data["lister_username"])
            category_slug = listing_data.pop("category_slug")
            lister_username = listing_data.pop("lister_username")
            category = None
            if category_slug:
                category = __import__("core.models", fromlist=["Category"]).Category.objects.filter(slug=category_slug).first()
            if category is None:
                continue

            listing, created = Listing.objects.update_or_create(
                slug=listing_data["slug"],
                defaults={
                    "lister": lister,
                    "category": category,
                    **listing_data,
                },
            )
            if created:
                created_listings += 1

        self.stdout.write(
            self.style.SUCCESS(
                f"Done. Created {created_users} new users, seeded {len(listings_data)} listings, and used MWK currency throughout."
            )
        )
