from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_current_user, get_db
from app.models.user import User
from app.schemas.user_oauth_account import (
    OAuthAccountListResponse,
    DeleteOAuthAccountRequest,
)
from app.services.user_oauth_account_service import (
    get_oauth_account_list,
    delete_oauth_account,
)

router = APIRouter(prefix="/oauth-account", tags=["oauth-account"])


@router.get(
    "/list",
    summary="获取授权账户列表",
    description="获取授权账户列表，支持按广告主ID、授权ID、广告账户名称筛选",
)
async def oauth_account_list(
    advertiser_id: str | None = Query(None, description="广告主账户ID"),
    oauth_id: str | None = Query(None, description="授权ID"),
    advertiser_name: str | None = Query(None, description="广告账户名称（模糊查询）"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> dict:
    """
    获取授权账户列表
    
    - **advertiser_id**: 广告主账户ID（可选）
    - **oauth_id**: 授权ID（可选）
    - **advertiser_name**: 广告账户名称，支持模糊查询（可选）
    - **page**: 页码，默认为1
    - **page_size**: 每页数量，默认为10，最大100
    """
    try:
        result = await get_oauth_account_list(
            db=db,
            page=page,
            page_size=page_size,
            advertiser_id=advertiser_id,
            oauth_id=oauth_id,
            advertiser_name=advertiser_name,
            user_id=current_user.id,
        )
       
        return {
            "code": 0,
            "message": "查询成功",
            "data": result["data"],
            "pagination": {
                "page": result["page"],
                "page_size": result["page_size"],
                "total": result["total"],
                "total_pages": result["total_pages"],
            },
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )


@router.get(
    "/delete",
    summary="删除授权账户",
    description="软删除授权账户",
)
async def delete_oauth_account_api(
    id: str = Query(..., description="授权账户表id"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
) -> dict:
    try:
        await delete_oauth_account(
            db=db,
            account_id=id,
            user_id=current_user.id,
        )
        
        return {
            "code": 0,
            "message": "删除成功",
        }
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e),
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e),
        )
