import os
from fastapi import APIRouter, Depends, HTTPException
from typing import Any, Dict
from modules.auth.supabase_bearer import SupabaseBearer
from modules.database.supabase.utils.client import SupabaseServiceRoleClient

router = APIRouter()
auth = SupabaseBearer()

@router.get("/cabinets")
def list_cabinets(payload: Dict[str, Any] = Depends(auth)):
    user_id = payload.get('sub') or payload.get('user_id')
    if not user_id:
        raise HTTPException(status_code=401, detail="Invalid token payload")
    client = SupabaseServiceRoleClient()
    # Owned + shared via membership
    owned = client.supabase.table('file_cabinets').select('*').eq('user_id', user_id).execute().data
    shared = client.supabase.table('cabinet_memberships').select('cabinet_id').eq('profile_id', user_id).execute().data
    shared_ids = [m['cabinet_id'] for m in (shared or [])]
    shared_rows = client.supabase.table('file_cabinets').select('*').in_('id', shared_ids).execute().data if shared_ids else []
    return {"owned": owned or [], "shared": shared_rows or []}

@router.post("/cabinets")
def create_cabinet(body: Dict[str, Any], payload: Dict[str, Any] = Depends(auth)):
    user_id = payload.get('sub') or payload.get('user_id')
    name = (body or {}).get('name')
    if not user_id or not name:
        raise HTTPException(status_code=400, detail="name is required")
    client = SupabaseServiceRoleClient()
    res = client.supabase.table('file_cabinets').insert({
        'user_id': user_id,
        'name': name
    }).execute()
    return res.data

@router.patch("/cabinets/{cabinet_id}")
def rename_cabinet(cabinet_id: str, body: Dict[str, Any], payload: Dict[str, Any] = Depends(auth)):
    name = (body or {}).get('name')
    if not name:
        raise HTTPException(status_code=400, detail="name is required")
    client = SupabaseServiceRoleClient()
    res = client.supabase.table('file_cabinets').update({'name': name}).eq('id', cabinet_id).execute()
    return res.data

@router.delete("/cabinets/{cabinet_id}")
def delete_cabinet(cabinet_id: str, payload: Dict[str, Any] = Depends(auth)):
    client = SupabaseServiceRoleClient()
    res = client.supabase.table('file_cabinets').delete().eq('id', cabinet_id).execute()
    return res.data

@router.post("/cabinets/{cabinet_id}/members")
def add_member(cabinet_id: str, body: Dict[str, Any], payload: Dict[str, Any] = Depends(auth)):
    target_profile_id = (body or {}).get('profile_id')
    role = (body or {}).get('role', 'viewer')
    if not target_profile_id:
        raise HTTPException(status_code=400, detail="profile_id required")
    client = SupabaseServiceRoleClient()
    # Insert membership (RLS will ensure only owner can do it)
    res = client.supabase.table('cabinet_memberships').upsert({
        'cabinet_id': cabinet_id,
        'profile_id': target_profile_id,
        'role': role
    }).execute()
    return res.data

@router.delete("/cabinets/{cabinet_id}/members/{profile_id}")
def remove_member(cabinet_id: str, profile_id: str, payload: Dict[str, Any] = Depends(auth)):
    client = SupabaseServiceRoleClient()
    res = client.supabase.table('cabinet_memberships').delete().match({
        'cabinet_id': cabinet_id,
        'profile_id': profile_id
    }).execute()
    return res.data


