from fastapi import APIRouter, HTTPException, Depends, Request
from typing import Optional
from app.db import database
from app.v1.models.saas.accountmodel import Account, AccountCreate, AccountUpdate, Accounts, AccountQueryParams
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.saas import accounts as account_service  # Adjust path as needed
from datetime import datetime

router = APIRouter()

@router.post("/", response_model=Account)
def create_account(
    account: AccountCreate, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        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=Accounts)
def get_accounts(
    params: AccountQueryParams = Depends(),
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user = Depends(get_current_userdetails)
):
    try:
        result = account_service.get_accounts_service(
            skip=params.skip,
            limit=params.limit,
            q=params.q,
            account_type=params.account_type,
            is_active=params.is_active,
            subscription_status=params.subscription_status,
            reg_date_from=params.reg_date_from,
            reg_date_to=params.reg_date_to,
            workforce_count_range=params.workforce_count_range,
            fleet_count_range=params.fleet_count_range,
            revenue_range=params.revenue_range,
            account_id=params.account_id,  # if needed
            db=db,
            current_user=current_user
        )
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/{account_id}", response_model=Account)
def get_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db)
):
    try:
        account = account_service.get_account_service(account_id, db)
        if account is None:
            raise HTTPException(status_code=404, detail="Account not found")
        return account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error retrieving account: {str(e)}")

@router.post("/{account_id}", response_model=Account)
def update_account(
    account_id: str,
    account: AccountUpdate,
    request: Request,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    try:
        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=Account)
def delete_account(
    account_id: str, 
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    try:
        if current_user.get('roles') > 1: 
            if current_user.get('account_id') != account_id:
                raise HTTPException(status_code=403, detail="Permission denied")
            # Check if the account exists before attempting to delete

        deleted_account = account_service.delete_account_service(account_id, db)
        if deleted_account is None:
            raise HTTPException(status_code=404, detail="Account not found")
        return deleted_account
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Error deleting account: {str(e)}")
