from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from typing import Optional

from app.database import get_db
from app.models.inspection import InspectionLocation, InspectionRecord
from app.schemas.inspection import (
    InspectionLocationCreate, InspectionLocationOut,
    InspectionRecordCreate, InspectionRecordOut,
)
from app.schemas.common import Response, PageResponse
from app.services.auth_service import get_current_user

router = APIRouter()


@router.get("/locations", response_model=Response[list[InspectionLocationOut]])
async def list_locations(
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    result = await db.execute(
        select(InspectionLocation).order_by(InspectionLocation.sort_order, InspectionLocation.id)
    )
    items = [InspectionLocationOut.model_validate(r) for r in result.scalars()]
    return Response.ok(items)


@router.post("/locations", response_model=Response[InspectionLocationOut])
async def create_location(
    body: InspectionLocationCreate,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    loc = InspectionLocation(**body.model_dump())
    db.add(loc)
    await db.flush()
    return Response.ok(InspectionLocationOut.model_validate(loc))


@router.get("/records", response_model=Response[PageResponse[InspectionRecordOut]])
async def list_records(
    page: int = 1,
    page_size: int = 30,
    location_id: Optional[int] = None,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    query = select(InspectionRecord).order_by(desc(InspectionRecord.created_at))
    if location_id:
        query = query.where(InspectionRecord.location_id == location_id)
    total = (await db.execute(select(func.count()).select_from(query.subquery()))).scalar()
    result = await db.execute(query.offset((page - 1) * page_size).limit(page_size))
    items = [InspectionRecordOut.model_validate(r) for r in result.scalars()]
    return Response.ok(PageResponse(total=total, page=page, page_size=page_size, items=items))


@router.post("/records", response_model=Response[InspectionRecordOut])
async def create_record(
    body: InspectionRecordCreate,
    db: AsyncSession = Depends(get_db),
    _ = Depends(get_current_user),
):
    loc_result = await db.execute(
        select(InspectionLocation).where(InspectionLocation.id == body.location_id)
    )
    loc = loc_result.scalar_one_or_none()
    record = InspectionRecord(
        **body.model_dump(),
        location_name=loc.name if loc else None,
    )
    db.add(record)
    await db.flush()
    return Response.ok(InspectionRecordOut.model_validate(record))
