"""Partner business logic."""

from typing import Optional, Tuple

from sqlalchemy.orm import Session

from ..models import Partner
from ..repositories import partners as partner_repo
from .security import generate_api_key, hash_api_key


def create_partner(db: Session, name: str, callback_url: Optional[str]) -> Tuple[Partner, str]:
    api_key = generate_api_key()
    partner = partner_repo.create_partner(db, name, callback_url, hash_api_key(api_key))
    return partner, api_key


def rotate_partner_key(db: Session, partner_id: str) -> Tuple[Partner, str]:
    partner = partner_repo.get_partner(db, partner_id)
    if not partner:
        raise ValueError("Partner not found")
    api_key = generate_api_key()
    partner = partner_repo.update_partner_key(db, partner, hash_api_key(api_key))
    return partner, api_key


def authenticate_partner(db: Session, api_key: str) -> Optional[Partner]:
    return partner_repo.get_partner_by_api_key_hash(db, hash_api_key(api_key))
