from sqlalchemy.orm import Session
from app.dao.lovelace_url_dao import LovelaceURLDAO
from app.model.lovelace_url_model import LovelaceURL


class LovelaceURLService:
    def __init__(self, db_session: Session):
        self.dao = LovelaceURLDAO(db_session)

    def list_all(self):
        return self.dao.get_all()

    def get_by_id(self, record_id: int):
        record = self.dao.get_by_id(record_id)
        if not record:
            raise ValueError(f"LovelaceURL with id {record_id} not found.")
        return record

    def create(self, room_name: str, url: str):
        if not room_name or not room_name.strip():
            raise ValueError("room_name cannot be empty.")
        if not url or not url.strip():
            raise ValueError("url cannot be empty.")

        record = LovelaceURL(room_name=room_name.strip(), url=url.strip())
        return self.dao.create(record)

    def update(self, record_id: int, room_name: str = None, url: str = None):
        record = self.get_by_id(record_id)

        if room_name is not None:
            if not room_name.strip():
                raise ValueError("room_name cannot be empty when provided.")
            record.room_name = room_name.strip()

        if url is not None:
            if not url.strip():
                raise ValueError("url cannot be empty when provided.")
            record.url = url.strip()

        return self.dao.update(record)

    def delete(self, record_id: int):
        record = self.get_by_id(record_id)
        self.dao.delete(record)
        return True


