from sqlalchemy import select, text

from scribe.models import async_session
from scribe.models.note_draft import NoteDraft


async def upsert_draft(
    user_id: int,
    note_id: int,
    proposed_body: str,
    original_body: str,
    instruction: str,
    scope: str,
) -> NoteDraft:
    async with async_session() as session:
        await session.execute(
            text("""
                INSERT INTO note_drafts (note_id, user_id, proposed_body, original_body, instruction, scope)
                VALUES (:note_id, :user_id, :proposed_body, :original_body, :instruction, :scope)
                ON CONFLICT (note_id, user_id) DO UPDATE SET
                    proposed_body = EXCLUDED.proposed_body,
                    original_body = EXCLUDED.original_body,
                    instruction   = EXCLUDED.instruction,
                    scope         = EXCLUDED.scope,
                    updated_at    = NOW()
            """).bindparams(
                note_id=note_id,
                user_id=user_id,
                proposed_body=proposed_body,
                original_body=original_body,
                instruction=instruction,
                scope=scope,
            )
        )
        await session.commit()
        result = await session.execute(
            select(NoteDraft).where(
                NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
            )
        )
        return result.scalars().first()


async def get_draft(user_id: int, note_id: int) -> NoteDraft | None:
    async with async_session() as session:
        result = await session.execute(
            select(NoteDraft).where(
                NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
            )
        )
        return result.scalars().first()


async def delete_draft(user_id: int, note_id: int) -> bool:
    async with async_session() as session:
        result = await session.execute(
            select(NoteDraft).where(
                NoteDraft.note_id == note_id, NoteDraft.user_id == user_id
            )
        )
        draft = result.scalars().first()
        if draft is None:
            return False
        await session.delete(draft)
        await session.commit()
        return True
