from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from datetime import datetime
from app.api.deps import get_current_user
from app.db.postgres import db

router = APIRouter()

class Job(BaseModel):
    id: str
    filename: str
    status: str
    quality_score: Optional[float]
    issues_found: Optional[int]
    fixes_applied: Optional[int]
    created_at: datetime
    completed_at: Optional[datetime]
    error: Optional[str]

@router.get("/", response_model=List[Job])
async def get_jobs(
    current_user: dict = Depends(get_current_user),
    limit: int = 50,
    offset: int = 0
):
    """Get job history for the current user."""
    query = """
        SELECT * FROM jobs 
        WHERE license_key = $1 
        ORDER BY created_at DESC 
        LIMIT $2 OFFSET $3
    """
    
    jobs = await db.fetch(query, current_user['license_key'], limit, offset)
    return jobs

@router.get("/{job_id}", response_model=Job)
async def get_job(
    job_id: str,
    current_user: dict = Depends(get_current_user)
):
    """Get a specific job."""
    query = "SELECT * FROM jobs WHERE id = $1 AND license_key = $2"
    job = await db.fetchrow(query, job_id, current_user['license_key'])
    
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
        
    return job
