from __future__ import annotations

import json
from datetime import datetime, timezone
from uuid import UUID

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.core.security.encryption import decrypt_value
from src.domain.domains.models import DomainOrder, WorkspaceDomain
from src.domain.domains.providers import CloudflareRegistrarProvider


async def fulfill_domain_registration(db: AsyncSession, order_id: UUID) -> None:
    """Fulfill exactly once after Stripe confirms the domain subscription payment."""
    order = await db.scalar(select(DomainOrder).where(DomainOrder.id == order_id).with_for_update())
    if not order or order.fulfillment_status in {"submitted", "active", "completed"}:
        return
    order.payment_status = "paid"
    metadata = dict(order.metadata_json or {})
    domain_name = metadata.get("domain_name")
    registrant_enc = metadata.get("registrant_enc")
    if not domain_name or not registrant_enc:
        order.fulfillment_status = "failed"
        return
    registrant = json.loads(decrypt_value(registrant_enc))
    years = int(metadata.get("years") or 1)
    auto_renew = bool(metadata.get("auto_renew", True))
    result = await CloudflareRegistrarProvider().register_domain(
        {"domain_name": domain_name, "contacts": {"registrant": registrant}, "years": years, "auto_renew": auto_renew},
        order.idempotency_key,
    )
    metadata["provider_registration_result"] = result
    order.metadata_json = metadata
    order.fulfillment_status = "submitted"
    domain = await db.scalar(select(WorkspaceDomain).where(WorkspaceDomain.normalized_domain == domain_name))
    if not domain:
        domain = WorkspaceDomain(
            workspace_id=order.workspace_id,
            domain_name=domain_name,
            normalized_domain=domain_name,
            domain_type="p2hs_registered",
            registrar_provider="cloudflare_registrar",
            registration_status="pending",
            verification_status="verified",
            auto_renew=auto_renew,
            renewal_authorized=auto_renew,
            metadata_json={"provider_registration_result": result},
        )
        db.add(domain)
        await db.flush()
    order.domain_id = domain.id
    await db.flush()
    registration = await CloudflareRegistrarProvider().get_registration(domain_name)
    domain.registration_status = "active" if registration.get("status") == "active" else "pending"
    domain.expires_at = _parse_dt(registration.get("expires_at"))
    domain.auto_renew = registration.get("auto_renew", auto_renew)
    domain.registrar_lock_status = registration.get("locked")
    order.fulfillment_status = "active" if domain.registration_status == "active" else "submitted"


def _parse_dt(value):
    if not value:
        return None
    return datetime.fromisoformat(value.replace("Z", "+00:00"))
