from typing import List, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, and_
from fastapi import HTTPException, status

from app.models.staff.store_model import Store, StoreProductInventory
from app.models.staff.staff_model import StaffStore
from app.models.listing.products import ProductListing, ManagerDiscount
from app.schemas.staff.store_schemas import StoreCreate, StoreUpdate


class StoreService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def create_store(self, store_data: StoreCreate, chain_id: int) -> Store:
        """Create a new store"""
        store_dict = store_data.dict()
        store_dict["chain_id"] = chain_id
        db_store = Store(**store_dict)
        self.db.add(db_store)
        await self.db.commit()
        await self.db.refresh(db_store)
        return db_store

    async def get_stores(self, chain_id: int, skip: int = 0, limit: int = 100) -> List[Store]:
        """Get all stores for a specific chain"""
        stmt = select(Store).where(Store.chain_id == chain_id).offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def get_store_by_id(self, store_id: int) -> Optional[Store]:
        """Get store by ID"""
        stmt = select(Store).where(Store.store_id == store_id)
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def update_store(self, store_id: int, store_data: StoreUpdate, chain_id: int) -> Optional[Store]:
        """Update a store"""
        # Verify store belongs to chain
        stmt = select(Store).where(
            and_(Store.store_id == store_id, Store.chain_id == chain_id)
        )
        result = await self.db.execute(stmt)
        db_store = result.scalar_one_or_none()
        
        if not db_store:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Store not found or does not belong to your chain"
            )
        
        # Update fields
        update_data = store_data.dict(exclude_unset=True)
        for field, value in update_data.items():
            if value is not None and hasattr(db_store, field):
                setattr(db_store, field, value)
        
        await self.db.commit()
        await self.db.refresh(db_store)
        return db_store

    async def delete_store(self, store_id: int, chain_id: int) -> bool:
        """Delete a store. Cannot delete if products, listings, inventory, or staff are linked."""
        # Verify store belongs to chain
        stmt = select(Store).where(
            and_(Store.store_id == store_id, Store.chain_id == chain_id)
        )
        result = await self.db.execute(stmt)
        db_store = result.scalar_one_or_none()
        
        if not db_store:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Store not found or does not belong to your chain"
            )
        
        # Check for linked staff assignments
        staff_stmt = select(StaffStore).where(StaffStore.store_id == store_id)
        staff_result = await self.db.execute(staff_stmt)
        staff_assignments = staff_result.scalars().all()
        
        if staff_assignments:
            staff_count = len(staff_assignments)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete store. {staff_count} staff member(s) are assigned to this store. Please unassign staff first."
            )
        
        # Check for product listings
        listings_stmt = select(ProductListing).where(ProductListing.store_id == store_id)
        listings_result = await self.db.execute(listings_stmt)
        listings = listings_result.scalars().all()
        
        if listings:
            listing_count = len(listings)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete store. {listing_count} product listing(s) are linked to this store. Please delete or reassign listings first."
            )
        
        # Check for inventory records
        inventory_stmt = select(StoreProductInventory).where(StoreProductInventory.store_id == store_id)
        inventory_result = await self.db.execute(inventory_stmt)
        inventory_records = inventory_result.scalars().all()
        
        if inventory_records:
            inventory_count = len(inventory_records)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete store. {inventory_count} inventory record(s) are linked to this store. Please delete inventory records first."
            )
        
        # Check for manager discount records
        discount_stmt = select(ManagerDiscount).where(ManagerDiscount.store_id == store_id)
        discount_result = await self.db.execute(discount_stmt)
        discount_records = discount_result.scalars().all()
        
        if discount_records:
            discount_count = len(discount_records)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete store. {discount_count} manager discount record(s) are linked to this store. Please delete discount records first."
            )
        
        # No dependencies found, safe to delete
        delete_stmt = delete(Store).where(Store.store_id == store_id)
        await self.db.execute(delete_stmt)
        await self.db.commit()
        return True
