from typing import List
from fastapi import HTTPException
from sqlalchemy.orm import Session
from app.api.company_list.schemas import CompanyListCreat, CompanyListResponse, CompanyListUpdate, VesselResponse
from app.models.main.company_list import CompanyListBase, TblCompanyList
from app.models.main.vessel_list import TblVesselList
from app.utils.schemas_utils import CustomResponse

class CompanyService:
    def __init__(self, db: Session, token: dict):
        self.db = db
        self.token = token

    async def create_company(self, request: CompanyListCreat):
        created_admin = CompanyListBase.model_validate(request)
        TblCompanyList.create(created_admin, self.db)
        self.db.commit()
        return CustomResponse(status="1", message="Company List created successfully")
    
    async def get_company(self, company_id: int) -> CompanyListResponse:
        company = self.db.query(TblCompanyList).filter(TblCompanyList.company_id == company_id).first()
        if not company:
            raise HTTPException(status_code=404, detail="Company not found")
        return CompanyListResponse.model_validate(company)
    
    async def get_company_vessels(self, company_id: int) -> list[VesselResponse]:
        vessels = self.db.query(TblVesselList).filter(TblVesselList.company_id == company_id).all()
        if not vessels:
            raise HTTPException(status_code=404, detail="No vessels found for this company")
        return [VesselResponse.model_validate(v) for v in vessels]
    
    async def update_company(self, request: CompanyListUpdate):
        company_base = CompanyListBase.model_validate(request)
        company = TblCompanyList.update(request.company_id, company_base, self.db)
        if not company:
            raise HTTPException(status_code=404, detail="Company not found")
        return CustomResponse(status="1", message="Company List updated successfully")
    
    async def get_all_companies(self) -> List[CompanyListBase]:
        results = self.db.query(TblCompanyList).all()
        return [CompanyListBase.model_validate(r) for r in results]


   