"""MediaAsset service."""
import uuid
from sqlalchemy import select, update as sql_update
from sqlalchemy.ext.asyncio import AsyncSession
from app.domains.media.models import MediaAsset, MediaAssetType


async def list_media_assets(
    db: AsyncSession,
    product_id: uuid.UUID | None = None,
    order_line_id: uuid.UUID | None = None,
    asset_type: MediaAssetType | None = None,
    is_archived: bool | None = False,
    skip: int = 0,
    limit: int = 50,
) -> list[MediaAsset]:
    q = select(MediaAsset).order_by(MediaAsset.created_at.desc())
    if product_id:
        q = q.where(MediaAsset.product_id == product_id)
    if order_line_id:
        q = q.where(MediaAsset.order_line_id == order_line_id)
    if asset_type:
        q = q.where(MediaAsset.asset_type == asset_type)
    if is_archived is not None:
        q = q.where(MediaAsset.is_archived == is_archived)
    q = q.offset(skip).limit(limit)
    result = await db.execute(q)
    return list(result.scalars().all())


async def get_media_asset(db: AsyncSession, asset_id: uuid.UUID) -> MediaAsset | None:
    result = await db.execute(select(MediaAsset).where(MediaAsset.id == asset_id))
    return result.scalar_one_or_none()


async def create_media_asset(db: AsyncSession, **kwargs) -> MediaAsset:
    asset = MediaAsset(**kwargs)
    db.add(asset)
    await db.commit()
    await db.refresh(asset)
    return asset


async def archive_media_asset(db: AsyncSession, asset_id: uuid.UUID) -> MediaAsset | None:
    await db.execute(
        sql_update(MediaAsset).where(MediaAsset.id == asset_id).values(is_archived=True)
    )
    await db.commit()
    return await get_media_asset(db, asset_id)


async def delete_media_asset(db: AsyncSession, asset_id: uuid.UUID) -> bool:
    asset = await get_media_asset(db, asset_id)
    if not asset:
        return False
    await db.delete(asset)
    await db.commit()
    return True


def get_download_url(asset: MediaAsset) -> str | None:
    """Get presigned URL from MinIO or local path."""
    try:
        from app.core.storage import get_storage
        storage = get_storage()
        return storage.get_url(asset.storage_key)
    except Exception:
        return f"/uploads/{asset.storage_key}"
