from fastapi import APIRouter, Depends, Query
from typing import Optional

from auth.models import TokenPayload
from auth.dependencies import require_permission
from crm.models import MediaCreate, MediaInDB, MediaListResponse
from crm import service

router = APIRouter(prefix="/api/crm/media", tags=["crm-media"])


@router.get("", response_model=MediaListResponse)
async def list_media(
    customer_id: Optional[str] = Query(None),
    order_id: Optional[str] = Query(None),
    _user: TokenPayload = Depends(require_permission("crm", "view")),
):
    items = await service.list_media(customer_id=customer_id, order_id=order_id)
    return MediaListResponse(items=items, total=len(items))


@router.post("", response_model=MediaInDB, status_code=201)
async def create_media(
    body: MediaCreate,
    _user: TokenPayload = Depends(require_permission("crm", "edit")),
):
    return await service.create_media(body)


@router.delete("/{media_id}", status_code=204)
async def delete_media(
    media_id: str,
    _user: TokenPayload = Depends(require_permission("crm", "edit")),
):
    await service.delete_media(media_id)
