from domain.offer import Offer
from use_cases.get_eligible_offers import GetEligibleOffersUseCase


class ResolveOfferByTitleUseCase:
    def __init__(self, get_eligible_offers: GetEligibleOffersUseCase):
        self._get_eligible_offers = get_eligible_offers

    async def execute(
        self, salon_id: str, client_id: str, offer_title: str
    ) -> str | None:
        normalized = offer_title.strip().lower()
        if not normalized:
            return None

        offers = await self._get_eligible_offers.execute(salon_id, client_id)
        match = self._find_match(normalized, offers)
        return match.id if match else None

    @staticmethod
    def _find_match(normalized: str, offers: list[Offer]) -> Offer | None:
        for offer in offers:
            title = offer.title.lower()
            if title == normalized:
                return offer

        for offer in offers:
            title = offer.title.lower()
            if normalized in title or title in normalized:
                return offer

        return None
