from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, EmailStr
from typing import List
from app.api.deps import get_current_user
from app.db.postgres import db
import uuid

router = APIRouter()

class Member(BaseModel):
    email: str
    role: str
    joined_at: str

class InviteRequest(BaseModel):
    email: EmailStr

@router.get("/members", response_model=List[Member])
async def get_members(current_user: dict = Depends(get_current_user)):
    """List all team members."""
    query = """
        SELECT email, role, joined_at 
        FROM team_members 
        WHERE license_key = $1
        UNION
        SELECT email, 'owner' as role, created_at as joined_at
        FROM licenses
        WHERE license_key = $1
    """
    rows = await db.fetch(query, current_user['license_key'])
    return [
        Member(
            email=r['email'], 
            role=r['role'], 
            joined_at=str(r['joined_at'])
        ) for r in rows
    ]

@router.post("/invite")
async def invite_member(
    request: InviteRequest,
    current_user: dict = Depends(get_current_user)
):
    """Invite a new member (Owner/Admin only)."""
    # Check permissions
    owner = await db.fetchval(
        "SELECT email FROM licenses WHERE license_key = $1",
        current_user['license_key']
    )
    
    if current_user['email'] != owner:
        role = await db.fetchval(
            "SELECT role FROM team_members WHERE license_key = $1 AND email = $2",
            current_user['license_key'],
            current_user['email']
        )
        if role != 'admin':
            raise HTTPException(status_code=403, detail="Only admins can invite members")

    # Create invite
    invite_id = str(uuid.uuid4())
    try:
        await db.execute(
            """
            INSERT INTO invites (id, license_key, email, role)
            VALUES ($1, $2, $3, 'member')
            """,
            invite_id,
            current_user['license_key'],
            request.email
        )
    except Exception:
        # Ignore duplicate invites for now
        pass
        
    # In a real app, we would send an email here
    return {"status": "invited", "invite_id": invite_id}
