from sqlalchemy.orm import Session

from app.core.exceptions import NotFoundError
from app.repositories.customer_repository import CustomerRepository
from app.repositories.vehicle_repository import VehicleRepository
from app.schemas.policy import VehicleCreate, VehicleResponse


class VehicleService:
    def __init__(self, db: Session):
        self.db = db
        self.customers = CustomerRepository(db)
        self.vehicles = VehicleRepository(db)

    def list_for_customer(self, agency_id: int, customer_id: int) -> list[VehicleResponse]:
        customer = self.customers.get_by_id(customer_id, agency_id)
        if not customer:
            raise NotFoundError("Customer not found")
        return [VehicleResponse.model_validate(v) for v in self.vehicles.list_by_customer(customer_id)]

    def create_for_customer(self, agency_id: int, customer_id: int, payload: VehicleCreate) -> VehicleResponse:
        customer = self.customers.get_by_id(customer_id, agency_id)
        if not customer:
            raise NotFoundError("Customer not found")
        vehicle = self.vehicles.create(customer_id, payload.model_dump())
        self.db.commit()
        self.db.refresh(vehicle)
        return VehicleResponse.model_validate(vehicle)
