from .base import BaseEntity, BaseRepository
from ..utils.utils import make_request


class OrganizationPhoneNumber(BaseEntity):
    def __init__(
        self,
        id: str = None,
        organization_id: str = None,
        phone_number: str = None,
        friendly_name: str = None,
        area_code: str = None,
        country_code: str = None,
        telephony_id: str = None,
        created_at: str = None,
        updated_at: str = None,
        deleted_at: str = None,
        **kwargs,
    ):
        self.id = id
        self.organization_id = organization_id
        self.phone_number = phone_number
        self.friendly_name = friendly_name
        self.area_code = area_code
        self.country_code = country_code
        self.telephony_id = telephony_id
        self.created_at = created_at
        self.updated_at = updated_at
        self.deleted_at = deleted_at or None


class OrganizationPhoneNumberRepository(BaseRepository[OrganizationPhoneNumber]):
    def __init__(self):
        super().__init__(
            "organization_phone_number",
            "/v1/organization-phone-numbers",
            OrganizationPhoneNumber,
        )

    def release(self, id: str) -> bool:
        response = make_request(f"{self.endpoint}/{id}/release", "POST")
        return response is not None

    def purchase(self, telephony_id: str, area_code: str = None, country_code: str = None, friendly_name: str = None) -> OrganizationPhoneNumber:
        body = {"telephonyId": telephony_id}
        if area_code is not None:
            body["areaCode"] = area_code
        if country_code is not None:
            body["countryCode"] = country_code
        if friendly_name is not None:
            body["friendlyName"] = friendly_name

        response = make_request(f"{self.endpoint}/purchase", "POST", json=body)

        if response and "data" in response:
            return self._create_entity(response["data"])

        return None
