from __future__ import annotations import logging from fastapi import APIRouter, Depends, HTTPException, Query from pydantic import BaseModel, Field from yuxi.channel.container import ChannelContainer, get_channel from yuxi.channel.interfaces.rest.auth.depends import channel_auth_depends logger = logging.getLogger(__name__) router = APIRouter() class BindingCreateRequest(BaseModel): channel_type: str = Field(..., min_length=1, max_length=20) account_id: str = Field(..., min_length=1, max_length=64) group_id: str = Field("", max_length=128) agent_config_id: int = Field(..., gt=0) class BindingResponse(BaseModel): id: int channel_type: str account_id: str group_id: str agent_config_id: int is_enabled: bool created_at: str class PaginatedMeta(BaseModel): total: int offset: int limit: int class BindingListResponse(BaseModel): items: list[BindingResponse] meta: PaginatedMeta @router.post("/channel/bindings", response_model=BindingResponse, status_code=201) async def create_binding( req: BindingCreateRequest, channel: ChannelContainer = Depends(get_channel), _: bool = Depends(channel_auth_depends), ): created = await channel.binding_service.create( channel_type=req.channel_type, account_id=req.account_id, group_id=req.group_id, agent_config_id=req.agent_config_id, ) return BindingResponse( id=created.id, channel_type=created.channel_type, account_id=created.account_id, group_id=created.group_id, agent_config_id=created.agent_config_id, is_enabled=created.is_enabled, created_at=created.created_at, ) @router.get("/channel/bindings", response_model=BindingListResponse) async def list_bindings( channel_type: str | None = None, offset: int = Query(0, ge=0), limit: int = Query(50, ge=1, le=200), channel: ChannelContainer = Depends(get_channel), _: bool = Depends(channel_auth_depends), ): bindings, total = await channel.binding_service.list( channel_type=channel_type, offset=offset, limit=limit, ) return BindingListResponse( items=[ BindingResponse( id=b.id, channel_type=b.channel_type, account_id=b.account_id, group_id=b.group_id, agent_config_id=b.agent_config_id, is_enabled=b.is_enabled, created_at=b.created_at, ) for b in bindings ], meta=PaginatedMeta(total=total, offset=offset, limit=limit), ) @router.delete("/channel/bindings/{binding_id}") async def delete_binding( binding_id: int, channel: ChannelContainer = Depends(get_channel), _: bool = Depends(channel_auth_depends), ): deleted = await channel.binding_service.delete(binding_id) if not deleted: raise HTTPException(status_code=404, detail="binding not found") return {"ok": True}