"""Conversion repository — all conversion data access via PocketBase."""
from __future__ import annotations

import structlog

import core.pocketbase as pb

log = structlog.get_logger()


class ConversionRepository:
    """Manages conversion records in PocketBase.

    Creating a record triggers the credit-deduction hook atomically.
    """

    async def create(self, user_id: str, file_hash: str, admin_token: str) -> str:
        """Create a pending conversion record. Returns the record ID.

        The PocketBase hook fires inside a SQLite transaction to deduct credits.
        Raises httpx.HTTPStatusError if user has insufficient credits.
        """
        return await pb.create_conversion(user_id, file_hash, admin_token)

    async def mark_complete(self, record_id: str, download_url: str, admin_token: str) -> None:
        """Mark a conversion complete and store the download URL."""
        await pb.update_conversion_download_url(record_id, download_url, admin_token)

    async def mark_failed(self, record_id: str, admin_token: str) -> None:
        """Mark a conversion failed, triggering the credit refund hook."""
        await pb.update_conversion_status(record_id, 'failed', admin_token)
