from fastapi import HTTPException
from sqlalchemy.orm import Session
from src.apps.stores import services
from src.apps.stores.schemas import StoreCreate, StoreResponse, BranchCreate, BranchResponse,StoreUpdate
from src.apps.users.models import User  # Ensure correct path
from src.apps.auth.controller import get_current_user  # Ensure get_current_user is correct
from src.apps.stores.models import Store,Branch
from src.apps.feedback.models import Feedback

import traceback

# ---------------- Store Controllers ----------------


def create_store_controller(store: StoreCreate, db: Session, current_user: User):
    try:
        # Ensure user doesn't already own a store
        existing_store = services.get_store_by_user(db, current_user)
        if existing_store:
            raise HTTPException(
                status_code=400,
                detail={"status": False, "code": 400, "message": "User already owns a store."}
            )

        # Ensure the store name is unique
        if services.get_store_by_name(db, store.name):
            raise HTTPException(
                status_code=400,
                detail={"status": False, "code": 400, "message": "Store name must be unique."}
            )

        # Create new store (returns a dictionary)
        new_store = services.create_store(db, store, current_user)

        return {
            "status": True,
            "code": 201,
            "message": "Store created successfully",
            "data": {
                "store_id": new_store["store_id"],
                "name": new_store["name"],
                "storetype_id": new_store["storetype_id"],  #  Include storetype_id
                "branch_limit": new_store["branch_limit"],
                "user_id": new_store["user_id"],
                "created_at": new_store["created_at"],
                "updated_at": new_store["updated_at"],
                "branches": [
                    {
                        "branch_id": branch["branch_id"],
                        "store_id": branch["store_id"],
                        "branch_name": branch["branch_name"],
                        "address": branch["address"],
                        "contact_info": branch["contact_info"],
                        "user_id": branch["user_id"],
                        "created_at": branch["created_at"],
                        "updated_at": branch["updated_at"],
                    }
                    for branch in new_store["branches"]
                ],
            }
        }

    except HTTPException as http_exc:
        raise http_exc

    except Exception as e:
        traceback.print_exc()
        raise HTTPException(
            status_code=500,
            detail={"status": False, "code": 500, "message": f"Internal server error: {str(e)}"}
        )


def get_store_controller(db: Session, current_user: User):
    try:
        store_data = services.get_store_by_user(db, current_user)

        if not store_data:
            raise HTTPException(
                status_code=404,
                detail={"status": False, "code": 404, "message": "Store not found or does not belong to the user."}
            )

        return {
            "status": True,
            "code": 200,
            "message": "Store details fetched successfully",
            "data": {
                "store_id": store_data.store_id,
                "name": store_data.name,
                "storetype_id": store_data.storetype_id,
                "branch_limit": store_data.branch_limit,  #  Include in response
                "user_id": store_data.user_id,
                "created_at": store_data.created_at,
                "updated_at": store_data.updated_at,
                "branches": [
                    {
                        "branch_id": branch.branch_id,
                        "store_id": branch.store_id,
                        "branch_name": branch.branch_name,
                        "address": branch.address,
                        "contact_info": branch.contact_info,
                        "created_at": branch.created_at,
                        "updated_at": branch.updated_at,
                        "user_id": branch.user_id
                    } for branch in store_data.branches
                ]
            }
        }

    except HTTPException:
        raise HTTPException(
            status_code=404,
            detail={"status": False, "code": 404, "message": "Store not found"}
        )


def update_store_controller(store_update: StoreUpdate, db: Session, current_user: User):
    # Fetch the store linked to the current user
    store = services.get_store_by_user(db, current_user)
    if not store:
        raise HTTPException(
            status_code=404, 
            detail={"status": False, "code": 404, "message": "Store not found"}
        )

    # Track changes
    updated = False

    # Update store name if provided and different from the current one
    if store_update.new_name and store.name != store_update.new_name:
        store.name = store_update.new_name
        updated = True

    # Update branch_limit if provided and different from the current value
    if store_update.branch_limit and store.branch_limit != store_update.branch_limit:
        store.branch_limit = store_update.branch_limit
        updated = True

    # If no updates were made, return an error
    if not updated:
        raise HTTPException(
            status_code=400, 
            detail={"status": False, "code": 400, "message": "No changes were made."}
        )

    # Commit changes to the database
    db.commit()
    db.refresh(store)

    return {
        "status": True,
        "code": 200,
        "message": "Store updated successfully",
        "data": {
            "store_id": store.store_id,
            "name": store.name,
            "branch_limit": store.branch_limit,
            "user_id": store.user_id,
            "created_at": store.created_at.isoformat(),
            "updated_at": store.updated_at.isoformat()
        }
    }

def delete_store_controller(db: Session, current_user: User):
    # Fetch the store_id based on the authenticated user's store
    store = services.get_store_by_user(db, current_user)
    if not store:
        raise HTTPException(status_code=404, detail={"status": False, "code": 404, "message":"Store not found or unauthorized"})
    
    # Pass the store_id from the retrieved store
    return services.delete_store(db, current_user)


# ---------------- Branch Controllers ----------------

def create_branch_controller(branch, db: Session, current_user: User):
    return services.create_branch(db, branch, current_user)



def get_branches_by_store_id_controller(store_id: str, db: Session, current_user: User):
    try:
        branches = services.get_branches_by_store_id(db, store_id, current_user)
        
        if not branches:
            raise HTTPException(
                status_code=404,
                detail={"status": False, "code": 404, "message": "No branches found for this store"}
            )
            

        return {
            "status": True,
            "code": 200,
            "message": "Branches fetched successfully",
            "data": [
                {
                    "branch_id": branch.branch_id,
                    "store_id": branch.store_id,
                    "branch_name": branch.branch_name,
                    "address": branch.address,
                    "contact_info": branch.contact_info,
                    "created_at": branch.created_at,
                    "updated_at": branch.updated_at,
                    "user_id": branch.user_id
                } for branch in branches
            ]
        }
    
    except HTTPException as e:
        raise HTTPException(
                status_code=500,
                detail={"status": False, "code": 500, "message": str(e.detail)}
            )
       




def get_branch_by_id_controller(store_id: str, branch_id: str, db: Session, current_user: User):
    try:
        branch = services.get_branch_by_id(db, store_id, branch_id, current_user)

        if not branch:
            raise HTTPException(
                status_code=404,
                detail={"status": False, "code": 404, "message":"Branch not found or does not belong to the user."}
            )

        return {
            "status": True,
            "code": 200,
            "message": "Branch details fetched successfully",
            "data": {
                "branch_id": branch.branch_id,
                "store_id": branch.store_id,
                "branch_name": branch.branch_name,
                "address": branch.address,
                "contact_info": branch.contact_info,
                "created_at": branch.created_at,
                "updated_at": branch.updated_at,
                "user_id": branch.user_id
            }
        }

    except HTTPException as e:
        raise HTTPException(
                status_code= 500,
                detail={"status": False, "code": 500, "message":str(e.detail)}
            )
       


def update_branch_controller(branch_id: str, branch: BranchCreate, db: Session, current_user: User):
    return services.update_branch(db, branch_id, branch, current_user)


def delete_branch_controller(branch_id: str, db: Session, current_user: User):
    return services.delete_branch(db, branch_id, current_user)