from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from app import models
from app.schemas.category import CategoryCreate, CategoryUpdate, CategoryPublic
from app.database import get_session
from app.auth import current_active_user
from app.crud import category as crud_category, group as crud_group

router = APIRouter()

@router.post("/", response_model=CategoryPublic)
async def create_category(
    category_in: CategoryCreate,
    group_id: Optional[int] = None,
    db: AsyncSession = Depends(get_session),
    current_user: models.User = Depends(current_active_user),
):
    if group_id:
        is_member = await crud_group.is_user_member(db, user_id=current_user.id, group_id=group_id)
        if not is_member:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not a member of this group")
    
    return await crud_category.create_category(db=db, category_in=category_in, user_id=current_user.id, group_id=group_id)

@router.get("/", response_model=List[CategoryPublic])
async def read_categories(
    group_id: Optional[int] = None,
    db: AsyncSession = Depends(get_session),
    current_user: models.User = Depends(current_active_user),
):
    if group_id:
        is_member = await crud_group.is_user_member(db, user_id=current_user.id, group_id=group_id)
        if not is_member:
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not a member of this group")
        return await crud_category.get_group_categories(db=db, group_id=group_id)
    return await crud_category.get_user_categories(db=db, user_id=current_user.id)

@router.put("/{category_id}", response_model=CategoryPublic)
async def update_category(
    category_id: int,
    category_in: CategoryUpdate,
    db: AsyncSession = Depends(get_session),
    current_user: models.User = Depends(current_active_user),
):
    db_category = await crud_category.get_category(db, category_id=category_id)
    if not db_category:
        raise HTTPException(status_code=404, detail="Category not found")
    if db_category.user_id != current_user.id:
        if not db_category.group_id:
            raise HTTPException(status_code=403, detail="Not your category")
        is_member = await crud_group.is_user_member(db, user_id=current_user.id, group_id=db_category.group_id)
        if not is_member:
            raise HTTPException(status_code=403, detail="Not a member of this group")
    
    return await crud_category.update_category(db=db, db_category=db_category, category_in=category_in)

@router.delete("/{category_id}", response_model=CategoryPublic)
async def delete_category(
    category_id: int,
    db: AsyncSession = Depends(get_session),
    current_user: models.User = Depends(current_active_user),
):
    db_category = await crud_category.get_category(db, category_id=category_id)
    if not db_category:
        raise HTTPException(status_code=404, detail="Category not found")
    if db_category.user_id != current_user.id:
        if not db_category.group_id:
            raise HTTPException(status_code=403, detail="Not your category")
        is_member = await crud_group.is_user_member(db, user_id=current_user.id, group_id=db_category.group_id)
        if not is_member:
            raise HTTPException(status_code=403, detail="Not a member of this group")

    return await crud_category.delete_category(db=db, db_category=db_category) 