"""平台账号 CRUD 路由

统一入口 /api/accounts，写操作（POST/PUT/DELETE）受 API Key 保护。
资产的 Asset.account 按名称引用账号；重命名账号时服务层会同步更新引用资产。
"""

from typing import List

from fastapi import APIRouter, Depends
from sqlmodel import Session

from app.core.security import require_api_key
from app.database import get_session
from app.schemas.account import AccountCreate, AccountRead, AccountUpdate
from app.services import account_service

router = APIRouter(prefix="/api/accounts", tags=["accounts"])


@router.get("", response_model=List[AccountRead], summary="账号列表（含关联资产数）")
def list_accounts(session: Session = Depends(get_session)):
    return account_service.list_accounts(session)


@router.post(
    "",
    response_model=AccountRead,
    status_code=201,
    summary="创建账号",
    dependencies=[Depends(require_api_key)],
)
def create_account(data: AccountCreate, session: Session = Depends(get_session)):
    return account_service.create_account(session, data)


@router.put(
    "/{account_id}",
    response_model=AccountRead,
    summary="更新账号（重命名会同步更新引用该账号的资产）",
    dependencies=[Depends(require_api_key)],
)
def update_account(
    account_id: int, data: AccountUpdate, session: Session = Depends(get_session)
):
    return account_service.update_account(session, account_id, data)


@router.delete(
    "/{account_id}",
    summary="删除账号（资产中已填的账号名不受影响）",
    dependencies=[Depends(require_api_key)],
)
def delete_account(account_id: int, session: Session = Depends(get_session)) -> dict:
    return account_service.delete_account(session, account_id)
