from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session

from app.core.response import error, ok
from app.db.models import User
from app.db.session import get_db
from app.deps import get_current_user
from app.schemas.models import TrainingPlanCreateRequest, TrainingRecordCreateRequest
from app.services import training as training_service

router = APIRouter(prefix="/api/training", tags=["Training"])


@router.get("/plans")
def list_plans(
    childId: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    plans = training_service.list_plans_for_child(db, current_user.id, childId)
    if plans is None:
        return JSONResponse(
            status_code=404,
            content=error(10004, "child_not_found", request.state.request_id),
        )
    return ok(
        {"list": [training_service.plan_to_dict(plan) for plan in plans]},
        request_id=request.state.request_id,
    )


@router.post("/plans", status_code=201)
def create_plan(
    body: TrainingPlanCreateRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    plan = training_service.create_plan(db, current_user.id, body)
    if not plan:
        return JSONResponse(
            status_code=404,
            content=error(10004, "child_not_found", request.state.request_id),
        )
    return ok(
        training_service.plan_to_dict(plan),
        message="created",
        request_id=request.state.request_id,
    )


@router.get("/plans/{plan_id}")
def get_plan(
    plan_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    plan = training_service.get_plan_for_user(db, current_user.id, plan_id)
    if not plan:
        return JSONResponse(
            status_code=404,
            content=error(10010, "plan_not_found", request.state.request_id),
        )
    return ok(training_service.plan_to_dict(plan), request_id=request.state.request_id)


@router.post("/plans/{plan_id}/records", status_code=201)
def create_record(
    plan_id: int,
    body: TrainingRecordCreateRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    record = training_service.create_record(db, current_user.id, plan_id, body)
    if not record:
        return JSONResponse(
            status_code=404,
            content=error(10010, "plan_not_found", request.state.request_id),
        )
    return ok(
        {
            "id": record.id,
            "planId": plan_id,
            "exerciseId": record.exercise_id,
            "score": record.score,
            "completed": record.completed,
            "createdAt": record.created_at.isoformat(),
        },
        message="created",
        request_id=request.state.request_id,
    )
