from __future__ import annotations

import logging
from typing import Any

from spherepay_mcp.ports.spherepay_gateway import SpherePayGateway

logger = logging.getLogger(__name__)


class BusinessRepService:
    """Orchestrates business representative creation and verification."""

    def __init__(self, gateway: SpherePayGateway):
        self._gw = gateway

    async def onboard_representative(
        self,
        customer_id: str,
        first_name: str,
        last_name: str,
        email: str,
        phone: str,
        date_of_birth: str,
        address: dict[str, Any],
        roles: list[str] | None = None,
        ownership_percentage: float | None = None,
        title: str | None = None,
    ) -> dict[str, Any]:
        """Create a business representative and initiate verification.

        Creates the representative, generates a face verification link,
        and submits verification for review.
        """
        payload: dict[str, Any] = {
            "customerId": customer_id,
            "firstName": first_name,
            "lastName": last_name,
            "email": email,
            "phone": phone,
            "dateOfBirth": date_of_birth,
            "address": address,
        }
        if roles:
            payload["roles"] = roles
        if ownership_percentage is not None:
            payload["ownershipPercentage"] = ownership_percentage
        if title:
            payload["title"] = title

        rep_result = await self._gw.create_business_rep(payload)
        rep_id = rep_result.get("data", rep_result).get("id", "")

        face_result = await self._gw.generate_rep_face_verification_link(rep_id)

        await self._gw.submit_rep_verification(rep_id)

        return {
            "representative": rep_result.get("data", rep_result),
            "face_verification_link": face_result.get("data", {}).get("link", face_result),
            "verification_submitted": True,
            "next_steps": [
                "Representative must complete face verification via the link",
                "Verification has been submitted for review",
                "Use get_customer to check overall business verification status",
            ],
        }
