import graphene
from graphene_django import DjangoObjectType
from django.contrib.contenttypes.models import ContentType
from ..models import KYCRequest, KYCRequestRussia
from ..temporal import KycWorkflowClient


class KYCRequestType(DjangoObjectType):
    class Meta:
        model = KYCRequest
        fields = '__all__'

    country_data = graphene.JSONString()
    workflow_status = graphene.String()

    def resolve_country_data(self, info):
        return self.get_country_data()


class KYCRequestRussiaType(DjangoObjectType):
    class Meta:
        model = KYCRequestRussia
        fields = '__all__'


class KYCRequestRussiaInput(graphene.InputObjectType):
    companyName = graphene.String(required=True)
    companyFullName = graphene.String(required=True)
    inn = graphene.String(required=True)
    kpp = graphene.String()
    ogrn = graphene.String()
    address = graphene.String(required=True)
    bankName = graphene.String(required=True)
    bik = graphene.String(required=True)
    correspondentAccount = graphene.String()
    contactPerson = graphene.String(required=True)
    contactEmail = graphene.String(required=True)
    contactPhone = graphene.String(required=True)


class CreateKYCRequestRussia(graphene.Mutation):
    class Arguments:
        input = KYCRequestRussiaInput(required=True)

    kyc_request = graphene.Field(KYCRequestType)
    success = graphene.Boolean()

    def mutate(self, info, input):
        # Get user_id from JWT token
        user_id = getattr(info.context, 'user_id', None)
        if not user_id:
            raise Exception("Not authenticated")

        # 1. Create Russia details
        russia_details = KYCRequestRussia.objects.create(
            company_name=input.companyName,
            company_full_name=input.companyFullName,
            inn=input.inn,
            kpp=input.kpp or '',
            ogrn=input.ogrn or '',
            address=input.address,
            bank_name=input.bankName,
            bik=input.bik,
            correspondent_account=input.correspondentAccount or '',
        )

        # 2. Create main KYCRequest with reference to details
        kyc_request = KYCRequest.objects.create(
            user_id=user_id,
            team_name=input.companyName,
            country_code='RU',
            contact_person=input.contactPerson,
            contact_email=input.contactEmail,
            contact_phone=input.contactPhone,
            content_type=ContentType.objects.get_for_model(KYCRequestRussia),
            object_id=russia_details.id,
        )

        # 3. Start Temporal workflow
        KycWorkflowClient.start(kyc_request)

        return CreateKYCRequestRussia(kyc_request=kyc_request, success=True)


class UserQuery(graphene.ObjectType):
    """User schema - ID token authentication"""
    kyc_requests = graphene.List(KYCRequestType)
    kyc_request = graphene.Field(KYCRequestType, uuid=graphene.String(required=True))

    def resolve_kyc_requests(self, info):
        # Filter by user_id from JWT token
        user_id = getattr(info.context, 'user_id', None)
        if not user_id:
            return []
        return KYCRequest.objects.filter(user_id=user_id)

    def resolve_kyc_request(self, info, uuid):
        user_id = getattr(info.context, 'user_id', None)
        if not user_id:
            return None
        try:
            return KYCRequest.objects.get(uuid=uuid, user_id=user_id)
        except KYCRequest.DoesNotExist:
            return None


class UserMutation(graphene.ObjectType):
    """User mutations - ID token authentication"""
    create_kyc_request_russia = CreateKYCRequestRussia.Field()


user_schema = graphene.Schema(query=UserQuery, mutation=UserMutation)
