from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from typing import Optional
from datetime import datetime

from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.models.platform.vendormodels import (
    Vendor,
    VendorBase,
    VendorCreate,
    VendorResponseList,
    VendorUpdate
)
from app.v1.services.platform.vendors import (
    create_vendor_service,
    get_vendors_service,
    read_vendor_service,
    update_vendor_service,
    delete_vendor_service
)

router = APIRouter()


@router.post("/", response_model=Vendor)
def create_vendor_endpoint(
    vendor: VendorBase,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    # Convert Pydantic model to dict and handle optional fields
    vendor_data = vendor.model_dump(exclude_unset=True)
    
    # Add user info
    vendor_data["account_id"] = current_user.get("account_id", "")
    vendor_data["user_id"] = current_user.get("user_id", "")
    
    # Handle empty optional fields
    optional_fields = ['tax_id', 'website', 'logo']
    for field in optional_fields:
        if field not in vendor_data or vendor_data[field] == "":
            vendor_data[field] = None
    
    result = create_vendor_service(vendor_data, db)
    return JSONResponse(
        content={"message": "Vendor created successfully", "vendor": result["vendor_data"]}
    )

@router.get("/list/{account_id}/", response_model=VendorResponseList)
def get_vendors(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    vendor_type: Optional[str] = None,
    status: Optional[str] = None,
    date_from: Optional[str] = None,
    date_to: Optional[str] = None,
    sort_by: Optional[str] = None,               # NEW
    sort_order: Optional[str] = "asc",           # NEW: defaults to ascending
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    print("date_todate_todate_todate_todate_toCHECKINGIGIGGIGIGGIGI")
    if account_id != "all" and account_id != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return get_vendors_service(account_id, skip, limit, q, vendor_type, status, date_from, date_to, sort_by, sort_order, db)

@router.get("/{vendor_id}", response_model=Vendor)
def read_vendor(
    vendor_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    vendor = read_vendor_service(vendor_id, db)
    
    if vendor.get("account_id") and vendor["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return vendor

@router.put("/{vendor_id}", response_model=Vendor)
def update_vendor(
    vendor_id: str,
    vendor_data: VendorUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_vendor = read_vendor_service(vendor_id, db)
    
    if existing_vendor.get("account_id") and existing_vendor["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return update_vendor_service(vendor_id, vendor_data, db)

@router.delete("/{vendor_id}", response_model=Vendor)
def delete_vendor(
    vendor_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: dict = Depends(get_current_userdetails)
):
    existing_vendor = read_vendor_service(vendor_id, db)
    
    if existing_vendor.get("account_id") and existing_vendor["account_id"] != current_user.get("account_id", ""):
        raise HTTPException(status_code=403, detail="Not authorized")
    
    return delete_vendor_service(vendor_id, db)