import re
from src.domain.entities.merchant import MerchantLocation
from src.domain.interfaces.merchant_repository import MerchantRepositoryInterface

class CreateMerchantLocationUseCase:
    def __init__(self, repository: MerchantRepositoryInterface):
        self.repository = repository

    def _slugify(self, text: str) -> str:
        text = text.lower().strip()
        text = re.sub(r'[^\w\s-]', '', text)
        text = re.sub(r'[\s_-]+', '-', text)
        text = re.sub(r'^-+|-+$', '', text)
        return text

    def execute(self, merchant_id: int, location_data: dict) -> MerchantLocation:
        # Generate slug from name if not provided
        if 'slug' not in location_data or not location_data['slug']:
            location_data['slug'] = self._slugify(location_data['name'])
        
        location = MerchantLocation(
            id=None,
            merchant_id=merchant_id,
            name=location_data['name'],
            slug=location_data['slug'],
            email=location_data.get('email'),
            phone=location_data.get('phone'),
            address=location_data.get('address'),
            city=location_data.get('city'),
            state=location_data.get('state'),
            pincode=location_data.get('pincode'),
            gst_number=location_data.get('gst_number'),
            landmark=location_data.get('landmark'),
            total_revenue_per_month=location_data.get('total_revenue_per_month'),
            percentage_of_sales_in_emi=location_data.get('percentage_of_sales_in_emi'),
            number_of_lenders=location_data.get('number_of_lenders'),
            number_of_visits=location_data.get('number_of_visits')
        )
        return self.repository.create_location(location)
