from fastapi import APIRouter, HTTPException, Depends, Request
from typing import Optional
from app.db import database
from app.v1.models.platform.pricingrules import PricingRule, PricingRules, PricingRuleStatusUpdate
from app.v1.models.saas.usersmodel import User  # Ensure you have a valid User model
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.services.platform import pricingrules as account_service  # Adjust path as needed

# Import service functions
from ...services.platform.pricingrules import (
    get_users_service,
    update_account_service,
    delete_account_service,
    update_pricingrules_service,
    update_record_status
)


router = APIRouter()

@router.post("/", response_model=PricingRule)
def create_account(
    account: PricingRule, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):    
    try:
        print("PRICING CREATE ACCOUTNT 26")
        created_account = account_service.create_account_service(account, db)
        return created_account
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/", response_model=PricingRules)
def get_accounts(
    skip: int = 0, 
    limit: int = 10, 
    q: Optional[str] = None,
    account_type: Optional[str] = None,
    status: Optional[str] = None,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):

    try:
        print("get_accountsget_accounts 35")
        result = account_service.get_accounts_service(skip, limit, q, account_type, status, db, current_user)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/{account_id}", response_model=PricingRule)
def get_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):

    try:
        print("get_accountget_account 47")
        account = account_service.get_account_service(account_id, db)
        if account is None:
            raise HTTPException(status_code=404, detail="PricingRule not found")
        return account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error retrieving PricingRule: {str(e)}")

@router.post("/{account_id}", response_model=PricingRule)
def update_account(
    account_id: str,
    account: PricingRule,
    request: Request,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    print("update_accountupdate_account 656666666666666666666666666666666666666666666")
    try:
        print("update_accountupdate_account 65")
        updated_account = account_service.update_account_service(account_id, account, current_user, db)
        return updated_account
    except HTTPException as he:
        raise he
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.delete("/{account_id}", response_model=PricingRule)
def delete_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    print("delete_accountdelete_account 79")
    try:
        deleted_account = account_service.delete_account_service(account_id, db)
        if deleted_account is None:
            raise HTTPException(status_code=404, detail="Pricing Rule not found")
        return deleted_account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error deleting PricingRule: {str(e)}")

@router.get("/list/{account_id}/", response_model=PricingRules)
def get_users(
    account_id: str,
    skip: int = 0,
    limit: int = 10,
    q: Optional[str] = None,
    status: Optional[str] = None,
    pricing_type: Optional[str] = None,
    is_active: Optional[bool] = None,
    created_date_from: Optional[str] = None,
    created_date_to: Optional[str] = None,
    sort_by: Optional[str] = None,          
    sort_order: Optional[str] = "asc",      
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    """
    Returns a list of users for the given account.
    """
    print("listlistlistlist 1022222")
    return get_users_service(account_id, skip, limit, q, status, pricing_type, is_active, created_date_from, created_date_to, sort_by, sort_order, db, current_user)

@router.put("/{account_id}", response_model=PricingRule)
async def update_pricingrules(
    account_id: str,
    role_update: PricingRule,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    """
    Update an existing role.
    """
    if current_user.get("roles", 0) != 1 and current_user.get("roles", 0) != 100 and not current_user.get("is_account_admin", False):
        raise HTTPException(status_code=403, detail="Not authorized to update roles")
    try:
        print("account_idaccount_idaccount_idaccount_id11112222555")
        print(account_id)
        updated_role = await update_pricingrules_service(account_id, role_update, db)
        if not updated_role:
            raise HTTPException(status_code=404, detail="Pricing Rule not found")
        return updated_role
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{account_id}/update-status", response_model=PricingRuleStatusUpdate)
async def update_pricingrules_status(
    account_id: str,
    role_update: PricingRuleStatusUpdate,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user=Depends(get_current_userdetails)
):   
    
    if current_user.get("roles", 0) != 1 and not current_user.get("is_account_admin", False):
        raise HTTPException(status_code=403, detail="Not authorized to update roles")
    try:
        print("account_idaccount_idaccount_idaccount_id11112222555ss",role_update)
        print(account_id)
        updated_role = await update_record_status(account_id, role_update, db)

        if not updated_role:
            raise HTTPException(status_code=404, detail="PricingRule not found")
        return updated_role
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
