"""Job(프로젝트) 라우터 — tkuser API 프록시"""
from fastapi import APIRouter, Depends, HTTPException, Request
from ..auth.middleware import get_current_user
from ..utils.tkuser_client import get_token_from_request, get_projects, get_project

router = APIRouter()


@router.get("/")
async def get_jobs(request: Request, user: dict = Depends(get_current_user)):
    """프로젝트 목록 조회 (tkuser 프록시)"""
    token = get_token_from_request(request)
    projects = await get_projects(token, active_only=True)
    return {
        "success": True,
        "total_count": len(projects),
        "jobs": [
            {
                "job_no": p.get("job_no"),
                "job_name": p.get("project_name"),
                "client_name": p.get("client_name"),
                "status": "진행중" if p.get("is_active") else "완료",
                "created_at": p.get("created_at"),
                "project_name": p.get("project_name"),
            }
            for p in projects
        ],
    }


@router.get("/{job_no}")
async def get_job(job_no: str, request: Request, user: dict = Depends(get_current_user)):
    """프로젝트 상세 조회 — tkeg는 job_no로 참조하므로 목록에서 필터"""
    token = get_token_from_request(request)
    projects = await get_projects(token, active_only=False)
    matched = next((p for p in projects if p.get("job_no") == job_no), None)
    if not matched:
        raise HTTPException(status_code=404, detail="Job을 찾을 수 없습니다")
    return {
        "success": True,
        "job": {
            "job_no": matched.get("job_no"),
            "job_name": matched.get("project_name"),
            "client_name": matched.get("client_name"),
            "status": "진행중" if matched.get("is_active") else "완료",
            "created_at": matched.get("created_at"),
        },
    }
