"""Partner data access helpers."""

from typing import Optional

from sqlalchemy.orm import Session

from ..models import Partner


def get_partner(db: Session, partner_id: str) -> Optional[Partner]:
    return db.get(Partner, partner_id)


def get_partner_by_api_key_hash(db: Session, api_key_hash: str) -> Optional[Partner]:
    return db.query(Partner).filter(Partner.api_key_hash == api_key_hash).first()


def create_partner(
    db: Session, name: str, callback_url: Optional[str], api_key_hash: str
) -> Partner:
    partner = Partner(name=name, callback_url=callback_url, api_key_hash=api_key_hash)
    db.add(partner)
    db.commit()
    db.refresh(partner)
    return partner


def update_partner_key(db: Session, partner: Partner, api_key_hash: str) -> Partner:
    partner.api_key_hash = api_key_hash
    db.commit()
    db.refresh(partner)
    return partner
