from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import uuid


class KYCRequest(models.Model):
    """Главная модель KYC заявки. Ссылается на детали страны через ContentType."""
    WORKFLOW_STATUS_CHOICES = [
        ('pending', 'Ожидает обработки'),
        ('active', 'Активен'),
        ('error', 'Ошибка'),
    ]

    uuid = models.CharField(max_length=100, unique=True, default=uuid.uuid4)
    user_id = models.CharField(max_length=255, db_index=True)
    team_name = models.CharField(max_length=200, blank=True)
    country_code = models.CharField(max_length=2, blank=True)
    workflow_status = models.CharField(
        max_length=20,
        choices=WORKFLOW_STATUS_CHOICES,
        default='pending',
    )
    score = models.IntegerField(default=0)

    # Общие контактные данные
    contact_person = models.CharField(max_length=255, blank=True, default='')
    contact_email = models.EmailField(blank=True, default='')
    contact_phone = models.CharField(max_length=50, blank=True, default='')

    # Ссылка на детали страны через ContentType
    content_type = models.ForeignKey(
        ContentType,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='kyc_requests'
    )
    object_id = models.PositiveIntegerField(null=True, blank=True)
    country_details = GenericForeignKey('content_type', 'object_id')

    approved_by = models.CharField(max_length=255, null=True, blank=True)
    approved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'kyc_requests'

    def __str__(self):
        return f"KYC {self.user_id} - {self.workflow_status}"

    def get_country_data(self) -> dict:
        """Получить данные страны как словарь для Temporal workflow."""
        if self.country_details and hasattr(self.country_details, 'to_dict'):
            return self.country_details.to_dict()
        return {}


class KYCRequestRussia(models.Model):
    """Детали KYC для России. Отдельная модель без наследования."""

    # Данные компании от DaData
    company_name = models.CharField(max_length=255)
    company_full_name = models.TextField()
    inn = models.CharField(max_length=12)
    kpp = models.CharField(max_length=9, blank=True)
    ogrn = models.CharField(max_length=15, blank=True)
    address = models.TextField()

    # Банковские реквизиты
    bank_name = models.CharField(max_length=255)
    bik = models.CharField(max_length=9)
    correspondent_account = models.CharField(max_length=20, blank=True)

    class Meta:
        db_table = 'kyc_details_russia'

    def __str__(self):
        return f"KYC Russia: {self.company_name} (ИНН: {self.inn})"

    def to_dict(self) -> dict:
        """Конвертировать в словарь для передачи в Temporal workflow."""
        return {
            "company_name": self.company_name,
            "company_full_name": self.company_full_name,
            "inn": self.inn,
            "kpp": self.kpp,
            "ogrn": self.ogrn,
            "address": self.address,
            "bank_name": self.bank_name,
            "bik": self.bik,
            "correspondent_account": self.correspondent_account,
        }
