from __future__ import annotations

import sqlalchemy as sa
from geoalchemy2.elements import WKTElement
from sqlalchemy.orm import Session

from backend.app.db.models import Station
from backend.app.models import StationCreate
from backend.app.repositories.base import BaseRepository


class StationRepository(BaseRepository[Station]):
    model = Station

    def __init__(self, session: Session) -> None:
        super().__init__(session)

    def list_active(self) -> list[Station]:
        statement = sa.select(self.model).where(self.model.is_active.is_(True))
        return list(self.session.scalars(statement))

    @staticmethod
    def _point(latitude: float, longitude: float) -> WKTElement:
        return WKTElement(f"POINT({longitude} {latitude})", srid=4326)

    def create(self, data: StationCreate) -> Station:
        station = Station(
            name=data.name,
            osm_id=data.osm_id,
            code=data.code,
            location=self._point(data.latitude, data.longitude),
            elevation_m=data.elevation_m,
            is_active=data.is_active,
        )
        self.session.add(station)
        return station
