from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from uuid import UUID

from app.core.database import get_db
from app.core.security import get_current_user, require_permission
from app.models.core_models import LoginUsers
from app.models.rm_models import StationMaster
from sqlalchemy import select, nulls_last
from .schemas import StationCreate, StationUpdate, StationResponse
from .service import (
    list_stations_service,
    create_station_service,
    get_station_service,
    update_station_service,
    delete_station_service,
    permanent_delete_station_service
)

router = APIRouter()


@router.get("/dropdown", summary="Station dropdown list (any logged-in user)")
async def get_stations_dropdown(
    db: AsyncSession = Depends(get_db),
    _: LoginUsers = Depends(get_current_user),
):
    """Returns minimal station data for populating dropdowns.
    Only requires basic authentication — no special LOCATIONS permission needed.
    """
    stmt = (
        select(
            StationMaster.station_id,
            StationMaster.station_code,
            StationMaster.station_name,
            StationMaster.sequence_no,
        )
        .where(StationMaster.is_active == True)
        .distinct(StationMaster.station_code)
        .order_by(StationMaster.station_code, nulls_last(StationMaster.sequence_no))
    )
    result = await db.execute(stmt)
    rows = result.mappings().all()
    return [
        {
            "station_id": str(r["station_id"]),
            "station_code": r["station_code"],
            "station_name": r["station_name"],
            "sequence_no": r["sequence_no"],
        }
        for r in rows
    ]


@router.get("/", response_model=List[StationResponse])
async def list_stations(
    skip: int = 0,
    limit: int = 100,
    is_active: Optional[str] = None,
    db: AsyncSession = Depends(get_db),
    _=Depends(require_permission('LOCATIONS', 'view'))
):
    return await list_stations_service(
        db=db,
        skip=skip,
        limit=limit,
        is_active=is_active
    )


@router.post("/", response_model=StationResponse, status_code=201)
async def create_station(
    data: StationCreate,
    db: AsyncSession = Depends(get_db),
    _=Depends(require_permission('LOCATIONS', 'create'))
):
    return await create_station_service(db, data)


@router.get("/{station_id}", response_model=StationResponse)
async def get_station(
    station_id: UUID,
    db: AsyncSession = Depends(get_db),
    _=Depends(require_permission('LOCATIONS', 'view'))
):
    return await get_station_service(db, station_id)


@router.put("/{station_id}", response_model=StationResponse)
async def update_station(
    station_id: UUID,
    data: StationUpdate,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(require_permission('LOCATIONS', 'edit'))
):
    if user.role_code not in ('ADMIN', 'CLIENT_ADMIN', 'C_ADMIN'):
        raise HTTPException(status_code=403, detail="Only Admin and Client Admin can edit stations")
    return await update_station_service(db, station_id, data)


@router.delete("/{station_id}/permanent", status_code=204)
async def permanent_delete_station(
    station_id: UUID,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(require_permission('LOCATIONS', 'delete'))
):
    if user.role_code not in ('ADMIN', 'CLIENT_ADMIN', 'C_ADMIN'):
        raise HTTPException(status_code=403, detail="Only Admin and Client Admin can delete stations")
    await permanent_delete_station_service(db, station_id)


@router.delete("/{station_id}", status_code=204)
async def delete_station(
    station_id: UUID,
    db: AsyncSession = Depends(get_db),
    user: LoginUsers = Depends(require_permission('LOCATIONS', 'delete'))
):
    if user.role_code not in ('ADMIN', 'CLIENT_ADMIN', 'C_ADMIN'):
        raise HTTPException(status_code=403, detail="Only Admin and Client Admin can delete stations")
    await delete_station_service(db, station_id)