"""
Management command to create sample notifications for development/testing.
"""
import random
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.utils import timezone
from django.contrib.auth import get_user_model

from apps.services.notification.models import (
    Notification,
    NotificationCategory,
    NotificationChannel,
    NotificationStatus,
    NotificationPriority,
)
from apps.core.tenant.models import Tenant

User = get_user_model()


class Command(BaseCommand):
    help = 'Create sample notifications for testing'

    def add_arguments(self, parser):
        parser.add_argument(
            '--user-id',
            type=int,
            help='User ID to create notifications for',
        )
        parser.add_argument(
            '--count',
            type=int,
            default=15,
            help='Number of notifications to create',
        )
        parser.add_argument(
            '--clear',
            action='store_true',
            help='Clear existing notifications before creating new ones',
        )

    def handle(self, *args, **options):
        # Get tenant
        try:
            tenant = Tenant.objects.get(schema_name='public')
        except Tenant.DoesNotExist:
            self.stderr.write(self.style.ERROR('Tenant "public" not found'))
            return

        # Get or find user
        user_id = options.get('user_id')
        if user_id:
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                self.stderr.write(self.style.ERROR(f'User with ID {user_id} not found'))
                return
        else:
            user = User.objects.first()
            if not user:
                self.stderr.write(self.style.ERROR('No users found in database'))
                return

        self.stdout.write(f'Creating notifications for user: {user.email or user.phone or user.id}')

        # Clear existing if requested
        if options['clear']:
            deleted_count = Notification.objects.filter(user=user).delete()[0]
            self.stdout.write(f'Deleted {deleted_count} existing notifications')

        # Ensure categories exist
        categories = self._ensure_categories(tenant)
        
        # Sample notification data
        sample_notifications = [
            # System
            {
                'category': 'system',
                'title': 'خوش آمدید!',
                'content': 'به سیستم نکسا خوش آمدید. از امکانات مختلف سیستم استفاده کنید.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'system',
                'title': 'بروزرسانی سیستم',
                'content': 'سیستم در ساعت ۲۳:۰۰ برای بروزرسانی غیرفعال می‌شود.',
                'priority': NotificationPriority.HIGH,
            },
            {
                'category': 'system',
                'title': 'تنظیمات ذخیره شد',
                'content': 'تنظیمات حساب کاربری شما با موفقیت ذخیره شد.',
                'priority': NotificationPriority.LOW,
            },
            # Security
            {
                'category': 'security',
                'title': 'ورود جدید به حساب',
                'content': 'یک ورود جدید از دستگاه Windows 11 - Chrome شناسایی شد.',
                'priority': NotificationPriority.HIGH,
            },
            {
                'category': 'security',
                'title': 'رمز عبور تغییر کرد',
                'content': 'رمز عبور حساب کاربری شما با موفقیت تغییر کرد.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'security',
                'title': 'احراز هویت دو مرحله‌ای فعال شد',
                'content': 'احراز هویت دو مرحله‌ای برای حساب شما فعال شد.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'security',
                'title': '⚠️ تلاش ورود ناموفق',
                'content': '۳ تلاش ناموفق برای ورود به حساب شما ثبت شده است.',
                'priority': NotificationPriority.URGENT,
            },
            # Transaction
            {
                'category': 'transaction',
                'title': 'پرداخت موفق',
                'content': 'پرداخت شما به مبلغ ۵۰۰,۰۰۰ تومان با موفقیت انجام شد.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'transaction',
                'title': 'فاکتور جدید',
                'content': 'فاکتور شماره INV-2026-001 صادر شد. مبلغ: ۱,۲۰۰,۰۰۰ تومان',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'transaction',
                'title': 'بازپرداخت انجام شد',
                'content': 'مبلغ ۱۵۰,۰۰۰ تومان به حساب شما بازگردانده شد.',
                'priority': NotificationPriority.NORMAL,
            },
            # Social
            {
                'category': 'social',
                'title': 'دنبال‌کننده جدید',
                'content': 'علی محمدی شما را دنبال می‌کند.',
                'priority': NotificationPriority.LOW,
            },
            {
                'category': 'social',
                'title': 'نظر جدید',
                'content': 'مریم احمدی روی پست شما نظر گذاشت.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'social',
                'title': 'پیام جدید',
                'content': 'شما ۳ پیام خوانده نشده دارید.',
                'priority': NotificationPriority.NORMAL,
            },
            # Update
            {
                'category': 'update',
                'title': 'نسخه جدید منتشر شد',
                'content': 'نسخه ۲.۵.۰ با قابلیت‌های جدید منتشر شد. همین الان بروزرسانی کنید.',
                'priority': NotificationPriority.NORMAL,
            },
            {
                'category': 'update',
                'title': 'قابلیت جدید: داشبورد',
                'content': 'داشبورد جدید با گزارش‌های پیشرفته اضافه شد.',
                'priority': NotificationPriority.LOW,
            },
        ]

        count = options['count']
        created = 0

        for i in range(count):
            data = sample_notifications[i % len(sample_notifications)]
            category = categories.get(data['category'])
            
            # Random time in last 7 days
            random_days = random.uniform(0, 7)
            random_hours = random.uniform(0, 24)
            created_at = timezone.now() - timedelta(days=random_days, hours=random_hours)
            
            # Some should be read
            is_read = random.random() < 0.3  # 30% read
            read_at = created_at + timedelta(hours=random.uniform(0.5, 12)) if is_read else None
            
            notification = Notification.objects.create(
                tenant=tenant,
                user=user,
                category=category,
                channel=NotificationChannel.PANEL,
                title=data['title'],
                content=data['content'],
                priority=data['priority'],
                status=NotificationStatus.DELIVERED,
                is_read=is_read,
                read_at=read_at,
                sent_at=created_at,
                metadata={
                    'sample': True,
                    'index': i,
                },
            )
            # Update created_at manually
            Notification.objects.filter(pk=notification.pk).update(created_at=created_at)
            created += 1

        self.stdout.write(
            self.style.SUCCESS(f'Successfully created {created} notifications')
        )

    def _ensure_categories(self, tenant):
        """Ensure notification categories exist."""
        category_data = [
            {'name': 'system', 'label': 'سیستم', 'icon': 'cog', 'color': '#3B82F6'},
            {'name': 'security', 'label': 'امنیت', 'icon': 'shield', 'color': '#EF4444'},
            {'name': 'transaction', 'label': 'تراکنش', 'icon': 'currency', 'color': '#10B981'},
            {'name': 'social', 'label': 'اجتماعی', 'icon': 'users', 'color': '#8B5CF6'},
            {'name': 'update', 'label': 'بروزرسانی', 'icon': 'refresh', 'color': '#F59E0B'},
        ]

        categories = {}
        for data in category_data:
            category, created = NotificationCategory.objects.get_or_create(
                tenant=tenant,
                name=data['name'],
                defaults={
                    'label': data['label'],
                    'icon': data['icon'],
                    'color': data['color'],
                    'is_active': True,
                }
            )
            categories[data['name']] = category
            if created:
                self.stdout.write(f'Created category: {data["label"]}')

        return categories
