from typing import List, Optional
from app.models.entities import SubjectEntity
from app.schemas.requests import SubjectCreateRequest, SubjectUpdateRequest
from app.schemas.response import GetSubjectResponse
from app.repositories import SubjectRepository
from app.mapper import SubjectMapper


class SubjectService:
    def __init__(self, repository: SubjectRepository):
        self.repository = repository

    def create_subject(self, request: SubjectCreateRequest) -> str:
        subject = SubjectMapper.to_entity(request)
        return self.repository.create(subject)

    def get_all_subjects(self) -> List[GetSubjectResponse]:
        subjects = self.repository.get_all()
        return [
            GetSubjectResponse(
                id=str(subject.id),
                name=subject.name,
                alias=subject.short_name,
                description=subject.description,
            )
            for subject in subjects
        ]

    def get_subject_by_id(self, subject_id: str) -> Optional[GetSubjectResponse]:
        subject = self.repository.get_by_id(subject_id)
        if subject:
            return GetSubjectResponse(
                id=str(subject.id),
                name=subject.name,
                alias=subject.short_name,
                description=subject.description,
            )
        return None

    def update_subject(self, subject_id: str, request: SubjectUpdateRequest) -> bool:
        update_data = request.model_dump(exclude_unset=True)
        return self.repository.update(subject_id, update_data)

    def delete_subject(self, subject_id: str) -> bool:
        return self.repository.delete(subject_id)
