from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated, List
from app.database.database import get_db
from app.services.staff.staff_auth import StaffAuthService
from app.services.staff.store import StoreService
from app.utils.auth import get_current_user, get_admin_user, get_current_chain_id
from app.schemas.staff.store_schemas import StoreCreate, StoreUpdate, StoreSchema

router = APIRouter()
db_dependency = Annotated[AsyncSession, Depends(get_db)]


@router.post("/", response_model=StoreSchema, status_code=status.HTTP_201_CREATED)
async def create_store(
    store_data: StoreCreate,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """Create a new store (Admin only)"""
    service = StoreService(db)
    return await service.create_store(store_data, chain_id)


@router.get("/", response_model=List[StoreSchema])
async def get_stores(
    db: db_dependency,
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    current_user: dict = Depends(get_current_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """Get all stores for the current chain"""
    service = StoreService(db)
    return await service.get_stores(chain_id, skip=skip, limit=limit)


@router.get("/my-stores")
async def get_my_stores(db: db_dependency, current_user: dict = Depends(get_current_user)):
    """Get stores assigned to current staff member"""
    return await StaffAuthService(db).get_my_assigned_stores(int(current_user["sub"]))


@router.get("/{store_id}", response_model=StoreSchema)
async def get_store(
    store_id: int,
    db: db_dependency,
    current_user: dict = Depends(get_current_user)
):
    """Get a store by ID"""
    service = StoreService(db)
    store = await service.get_store_by_id(store_id)
    if not store:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Store not found"
        )
    return store


@router.put("/{store_id}", response_model=StoreSchema)
async def update_store(
    store_id: int,
    store_data: StoreUpdate,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """Update a store (Admin only). Admin can only update stores in their chain."""
    service = StoreService(db)
    store = await service.update_store(store_id, store_data, chain_id)
    if not store:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Store not found or does not belong to your chain"
        )
    return store


@router.delete("/{store_id}", status_code=status.HTTP_200_OK)
async def delete_store(
    store_id: int,
    db: db_dependency,
    admin_user: dict = Depends(get_admin_user),
    chain_id: int = Depends(get_current_chain_id)
):
    """
    Delete a store (Admin only). 
    
    Cannot delete if:
    - Staff members are assigned to the store
    - Product listings are linked to the store
    - Inventory records exist for the store
    - Manager discount records are linked to the store
    
    Admin can only delete stores in their chain.
    """
    service = StoreService(db)
    await service.delete_store(store_id, chain_id)
    return {"message": "Store deleted successfully", "store_id": store_id}
