from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from sqlalchemy.sql import func
from fastapi import HTTPException, status
import re
from datetime import datetime, UTC
from typing import Optional

from app.models.staff.store_model import Chain
from app.schemas.staff.chain_schemas import ChainCreateSchema


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

    def _generate_chain_code(self, chain_name: str) -> str:
        """Generate a chain_code from chain_name (uppercase, alphanumeric only)"""
        # Convert to uppercase and remove special characters, keep only alphanumeric
        chain_code = re.sub(r'[^A-Z0-9]', '', chain_name.upper())
        # If empty after cleaning, use a default
        if not chain_code:
            chain_code = "CHAIN"
        return chain_code

    async def create_chain(self, chain_request: ChainCreateSchema):
        """Create a new chain"""
        # Check if chain with same name already exists (excluding deleted chains)
        stmt = select(Chain).where(
            and_(
                Chain.chain_name == chain_request.chain_name,
                Chain.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        existing_chain = result.scalar_one_or_none()

        if existing_chain:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Chain with name '{chain_request.chain_name}' already exists",
            )

        # Generate chain_code from chain_name
        base_chain_code = self._generate_chain_code(chain_request.chain_name)
        chain_code = base_chain_code
        
        # Check if chain_code already exists (excluding deleted chains), if so make it unique
        stmt_code = select(Chain).where(
            and_(
                Chain.chain_code == chain_code,
                Chain.is_deleted == False
            )
        )
        result_code = await self.db.execute(stmt_code)
        existing_code = result_code.scalar_one_or_none()
        
        # If code exists, append a suffix to make it unique
        if existing_code:
            counter = 1
            while existing_code:
                chain_code = f"{base_chain_code}{counter}"
                stmt_code = select(Chain).where(
                    and_(
                        Chain.chain_code == chain_code,
                        Chain.is_deleted == False
                    )
                )
                result_code = await self.db.execute(stmt_code)
                existing_code = result_code.scalar_one_or_none()
                counter += 1

        # Create chain with chain_code and profit_percentage
        new_chain = Chain(
            chain_name=chain_request.chain_name,
            chain_code=chain_code,
            profit_percentage=chain_request.profit_percentage
        )
        self.db.add(new_chain)
        await self.db.commit()
        await self.db.refresh(new_chain)

        return {
            "message": "Chain created successfully",
            "status": True,
            "data": new_chain,
        }

    async def update_chain_code(self, chain_id: int, new_chain_code: str) -> Chain:
        """Update chain_code for a chain (Admin only)"""
        stmt = select(Chain).where(
            and_(
                Chain.chain_id == chain_id,
                Chain.is_deleted == False
            )
        )
        result = await self.db.execute(stmt)
        db_chain = result.scalar_one_or_none()
        
        if not db_chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Chain not found"
            )
        
        # Check if chain_code is already taken by another chain (excluding deleted chains)
        existing_stmt = select(Chain).where(
            and_(
                Chain.chain_code == new_chain_code,
                Chain.chain_id != chain_id,
                Chain.is_deleted == False
            )
        )
        existing_result = await self.db.execute(existing_stmt)
        if existing_result.scalar_one_or_none():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Chain code '{new_chain_code}' is already in use by another chain"
            )
        
        # Update chain_code
        db_chain.chain_code = new_chain_code
        await self.db.commit()
        await self.db.refresh(db_chain)
        return db_chain

    async def get_chain(self, chain_id: int, include_deleted: bool = False):
        """Get a specific chain by ID (excludes deleted chains by default)"""
        if include_deleted:
            stmt = select(Chain).where(Chain.chain_id == chain_id)
        else:
            stmt = select(Chain).where(
                and_(
                    Chain.chain_id == chain_id,
                    Chain.is_deleted == False
                )
            )
        result = await self.db.execute(stmt)
        chain = result.scalar_one_or_none()

        if not chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Chain with ID {chain_id} not found",
            )

        return {
            "message": "Chain retrieved successfully",
            "status": True,
            "data": chain,
        }

    async def get_all_chains(self, include_deleted: bool = False):
        """Get all chains (excludes deleted chains by default)"""
        if include_deleted:
            stmt = select(Chain)
        else:
            stmt = select(Chain).where(Chain.is_deleted == False)
        result = await self.db.execute(stmt)
        chains = result.scalars().all()

        return {
            "message": "Chains retrieved successfully",
            "status": True,
            "data": chains,
        }

    async def soft_delete_chain(self, chain_id: int) -> Chain:
        """Soft delete a chain (Superadmin only)
        
        This will:
        - Mark the chain as deleted
        - Block access for all staff (admins, managers, employees) of this chain
        - The chain and its data remain in the database but are hidden from normal operations
        """
        # Get chain (including deleted ones for this check)
        stmt = select(Chain).where(Chain.chain_id == chain_id)
        result = await self.db.execute(stmt)
        chain = result.scalar_one_or_none()
        
        if not chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Chain with ID {chain_id} not found"
            )
        
        if chain.is_deleted:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Chain with ID {chain_id} is already deleted"
            )
        
        # Soft delete the chain
        chain.is_deleted = True
        chain.deleted_at = datetime.now(UTC)
        
        await self.db.commit()
        await self.db.refresh(chain)
        
        return chain

    async def restore_chain(self, chain_id: int) -> Chain:
        """Restore a soft-deleted chain (Superadmin only)"""
        stmt = select(Chain).where(Chain.chain_id == chain_id)
        result = await self.db.execute(stmt)
        chain = result.scalar_one_or_none()
        
        if not chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Chain with ID {chain_id} not found"
            )
        
        if not chain.is_deleted:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Chain with ID {chain_id} is not deleted"
            )
        
        # Restore the chain
        chain.is_deleted = False
        chain.deleted_at = None
        
        await self.db.commit()
        await self.db.refresh(chain)
        
        return chain

    async def update_chain(self, chain_id: int, chain_name: Optional[str] = None, profit_percentage: Optional[float] = None) -> Chain:
        """Update chain name and/or profit_percentage (Superadmin only)
        
        Args:
            chain_id: ID of the chain to update
            chain_name: New chain name (optional, must be unique if provided)
            profit_percentage: New profit percentage (optional, 0-100)
        
        Returns:
            Updated Chain object
        """
        # Get chain (can include deleted chains for superadmin operations)
        stmt = select(Chain).where(Chain.chain_id == chain_id)
        result = await self.db.execute(stmt)
        db_chain = result.scalar_one_or_none()
        
        if not db_chain:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Chain with ID {chain_id} not found"
            )
        
        # Update chain_name if provided
        if chain_name is not None:
            # Check if chain_name is already taken by another chain (excluding deleted chains)
            existing_stmt = select(Chain).where(
                and_(
                    Chain.chain_name == chain_name,
                    Chain.chain_id != chain_id,
                    Chain.is_deleted == False
                )
            )
            existing_result = await self.db.execute(existing_stmt)
            if existing_result.scalar_one_or_none():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Chain name '{chain_name}' is already in use by another chain"
                )
            db_chain.chain_name = chain_name
        
        # Update profit_percentage if provided
        if profit_percentage is not None:
            db_chain.profit_percentage = profit_percentage
        
        await self.db.commit()
        await self.db.refresh(db_chain)
        
        return db_chain
