from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from db import get_db
from models.user import User
from typing import List
from schemas.schemas import UserUpdate
from schemas.user import UserOut

router = APIRouter()

# Get all stores
@router.get("/all-stores", response_model=List[UserOut])
def get_all_stores(db: Session = Depends(get_db)):
    return db.query(User).filter(User.role.in_(["STORE", "MAIN_STORE"])).all()


# Get all factories
@router.get("/all-factories", response_model=List[UserOut])
def get_all_factories(db: Session = Depends(get_db)):
    return db.query(User).filter(User.role == "FACTORY").all()

@router.put("/update-store/{store_id}", response_model=UserOut, tags=["Stores"])
def update_store(store_id: int, updated_data: UserUpdate, db: Session = Depends(get_db)):
    store = db.query(User).filter(User.id == store_id, User.role.in_(["STORE", "MAIN_STORE"])).first()
    if not store:
        raise HTTPException(status_code=404, detail="Store not found")

    for key, value in updated_data.dict(exclude_unset=True).items():
        setattr(store, key, value)

    db.commit()
    db.refresh(store)
    return store

@router.delete("/delete-store/{store_id}", tags=["Stores"])
def delete_store(store_id: int, db: Session = Depends(get_db)):
    store = db.query(User).filter(User.id == store_id, User.role.in_(["STORE", "MAIN_STORE"])).first()
    if not store:
        raise HTTPException(status_code=404, detail="Store not found")

    db.delete(store)
    db.commit()
    return {"detail": "Store deleted successfully"}
