from fastapi import APIRouter, Depends, Query, HTTPException, Path
from typing import Dict
from app.common.database import get_db
from app.common.models import Company
from app.schemas.company_schemas import CompanyCreate, CompanyUpdate, CompanyPatch
from ..services.auth_utils import validate_token

router = APIRouter()


@router.get("/companies/all")
async def read_all(
    limit: int = Query(10, ge=1, le=100),
    offset: int = Query(0, ge=0),
    db=Depends(get_db),
    current_user: Dict = Depends(validate_token),
):
    companies = db.query(Company).offset(offset).limit(limit).all()
    total_companies = db.query(Company).count()
    return {
        "limit": limit,
        "offset": offset,
        "total_count": total_companies,
        "data": companies,
    }


@router.get("/companies/{company_id}")
async def get_company(
    company_id: int = Path(..., ge=1),
    current_user: Dict = Depends(validate_token),
    db=Depends(get_db),
):
    company = db.query(Company).filter(Company.id == company_id).first()
    if not company:
        raise HTTPException(status_code=404, detail="Company not found")
    return company


@router.post("/companies")
async def create_company(
    company: CompanyCreate,
    current_user: Dict = Depends(validate_token),
    db=Depends(get_db),
):
    db_company = Company(**company.dict())
    db.add(db_company)
    db.commit()
    db.refresh(db_company)
    return db_company


@router.put("/companies/{company_id}")
async def update_company(
    company_id: int,
    updated_data: CompanyUpdate,
    current_user: Dict = Depends(validate_token),
    db=Depends(get_db),
):
    db_company = db.query(Company).filter(Company.id == company_id).first()
    if not db_company:
        raise HTTPException(status_code=404, detail="Company not found")

    for key, value in updated_data.dict().items():
        setattr(db_company, key, value)

    db.commit()
    db.refresh(db_company)
    return db_company


@router.patch("/companies/{company_id}")
async def patch_company(
    company_id: int,
    updated_data: CompanyPatch,
    db=Depends(get_db),
    current_user: Dict = Depends(validate_token),
):
    db_company = db.query(Company).filter(Company.id == company_id).first()
    if not db_company:
        raise HTTPException(status_code=404, detail="Company not found")

    for key, value in updated_data.dict(exclude_unset=True).items():
        setattr(db_company, key, value)

    db.commit()
    db.refresh(db_company)
    return db_company
