from fastapi import APIRouter, Depends, Form, HTTPException, Query, status,BackgroundTasks
from datetime import datetime, timedelta,timezone,date

from src.application_management.models import FinancialTag
from src.company_management.service import CompanyManagement
from src.core.database import get_db
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import desc, select
from src.auth.utils import pwd_context
#external services
from src.external.email import transporter
#models
from src.models.company import Company
from src.models.company_user import User
from src.models.application_user import ApplicationUser
from typing import Optional
from src.constants import TicketPriorityEnum
#schemas
from .schemas import AddUserRequest, Tag, TagList,TicketSchema


#global schemas
from src.schemas.application_user import CurrentApplicationUser

#global deps

from src.common.dependencies import get_current_application_user
from src.common.utils import add_delete_update_application_user_access_check


#constants
from src.constants import CompanyPlanEnum,TicketStatusEnum
#services

from .service import ApplicationManagement


application_management_router = APIRouter(prefix="/application/management", tags=["application management"])

@application_management_router.post("/add-user/",status_code=status.HTTP_201_CREATED)
async def add_user(requestBody: AddUserRequest, db: AsyncSession = Depends(get_db)):#,currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):

    
    try:
        
        #has_permission = add_delete_update_application_user_access_check(currentApplicationUser,action="add")


       # if not has_permission:
           # raise HTTPException(
              #  status_code=status.HTTP_403_FORBIDDEN,
              #  detail="You do not have permission to Application a user."
          #  ) 
        
        result = await ApplicationManagement.add_user(user_info = requestBody ,db = db)

        return result

    except HTTPException as e:

        raise e
    
@application_management_router.get("/tickets/")
async def get_ticket_applicationuser(
    page:int= Query(1,ge=1,description='page number'),
    limit: int = Query(10, ge=1, description='limit of tickets per page'),
    Issue_Type: Optional[str] = Query(None),
    Title: Optional[str] = Query(None),
    priority:Optional[TicketPriorityEnum]=Query(None),
    db:AsyncSession=Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
    '''
    get all tickets of user
    Parameters:

    - page(int):page number
    - limit(int):limit of tickets per page
    Returns
    -------

    returns dictionary containing list of tickets and pagination details
    '''
    try:
        result=await ApplicationManagement.get_ticket_alluser(page=page,limit=limit,title=Title,Issuetype=Issue_Type,priority=priority,db=db)
        return result
    except HTTPException as e:
        raise e
@application_management_router.put("/ticket/status/") 
async def update_ticket_status(status:TicketStatusEnum=Form(None),ticket_id:str=Form(None),db:AsyncSession=Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
    '''
    updating status of ticket by application user and sending email notification to it admin
   Parameters
    ----------
   status (str): status of ticket
    ticket_id (str):    id of ticket
    Returns
    -------
        returns dictionary containing success message
    '''
    try:
       
        result=await ApplicationManagement.update_ticket_status(status=status,ticket_id=ticket_id,db=db)
        return result
    except HTTPException as e:
        raise e









# @application_management_router.get("/tags")
# async def get_tags(db: AsyncSession = Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
#     try:
        

#         has_permission = add_delete_update_application_user_access_check(currentApplicationUser,action="add")


#         if not has_permission:
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="You do not have permission to Application a user."
#             )  
        
#         stmt = select(FinancialTag).order_by(desc(FinancialTag.created_at))
#         result = await db.execute(stmt)
#         tags = result.scalars().all()

#         return [{"id": tag.id, "tag_name": tag.tag_name} for tag in tags]
#     except Exception as e:
#         raise e

# @application_management_router.post("/tags", status_code=201)
# async def create_tags(tag_list: TagList, db: AsyncSession = Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
#     # Extract all tag names
#     try :
        

#         has_permission = add_delete_update_application_user_access_check(currentApplicationUser,action="add")


#         if not has_permission:
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="You do not have permission to Application a user."
#             ) 
        
#         incoming_tag_names = [tag.tag_name for tag in tag_list.tags]

#         # Fetch existing tags from DB
#         result = await db.execute(select(FinancialTag.tag_name).where(FinancialTag.tag_name.in_(incoming_tag_names)))
#         existing_names = set(result.scalars().all())

#         # Filter out duplicates
#         new_tags = [
#             FinancialTag(tag_name=name,user_id=currentApplicationUser.user_id)
#             for name in incoming_tag_names
#             if name not in existing_names
#         ]

#         if not new_tags:
#             raise HTTPException(status_code=400, detail="tag name already exist")

#         db.add_all(new_tags)
#         await db.commit()

#         return [{"id": tag.id, "tag_name": tag.tag_name} for tag in new_tags]
#     except Exception as e:
#         raise e

# @application_management_router.put("/tags/{tag_id}")
# async def update_tag(tag_id: int, tag: Tag, db: AsyncSession = Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
#     try :
#         has_permission = add_delete_update_application_user_access_check(currentApplicationUser,action="add")


#         if not has_permission:
#             raise HTTPException(
#                 status_code=status.HTTP_403_FORBIDDEN,
#                 detail="You do not have permission to Application a user."
#             ) 
#         result = await db.execute(select(FinancialTag).where(FinancialTag.id == tag_id))
#         existing_tag = result.scalars().first()
#         if not existing_tag:
#             raise HTTPException(status_code=404, detail="Tag not found")

#         # Check for duplicate tag_name
#         result = await db.execute(
#             select(FinancialTag).where(
#                 FinancialTag.tag_name == tag.tag_name,
#                 FinancialTag.id != tag_id
#             )
#         )
#         duplicate = result.scalars().first()
#         if duplicate:
#             raise HTTPException(status_code=400, detail="Tag name already in use")

#         existing_tag.tag_name = tag.tag_name
#         await db.commit()
#         await db.refresh(existing_tag)
#         return {"id": existing_tag.id, "tag_name": existing_tag.tag_name}
#     except Exception as e:
#         raise e

# @application_management_router.delete("/tags/{tag_id}", status_code=204)
# async def delete_tag(tag_id: int, db: AsyncSession = Depends(get_db),currentApplicationUser: CurrentApplicationUser = Depends(get_current_application_user)):
    # try :
    #     has_permission = add_delete_update_application_user_access_check(currentApplicationUser,action="add")


    #     if not has_permission:
    #         raise HTTPException(
    #             status_code=status.HTTP_403_FORBIDDEN,
    #             detail="You do not have permission to Application a user."
    #         ) 
    #     result = await db.execute(select(FinancialTag).where(FinancialTag.id == tag_id))
    #     existing_tag = result.scalars().first()
    #     if not existing_tag:
    #         raise HTTPException(status_code=404, detail="Tag not found")

    #     await db.delete(existing_tag)
    #     await db.commit()
    #     return {"messsage":"deleted successfully"}
    # except Exception as e:
    #     raise e