from pathlib import Path

from src.domain.codegen.legacy_form_uploads import (
    find_legacy_upload_candidates,
    migrate_legacy_upload_candidate,
)


def _write(root: Path, relative: str, content: str) -> None:
    path = root / relative
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")


def test_migrates_presign_only_nuxt_upload_and_is_idempotent(tmp_path: Path):
    route = "server/api/registration/upload.post.ts"
    client = "composables/useRegistrationForm.ts"
    _write(
        tmp_path,
        route,
        """import { cloudFetch } from '~/server/utils/p2hs'\nconst BUCKET = 'student-documents'\nexport default defineEventHandler(async (event) => {\n  const body = await readBody(event)\n  const presign = await cloudFetch(event, `storage/${BUCKET}/presign`, { method: 'POST', body })\n  return presign\n})\n""",
    )
    _write(
        tmp_path,
        client,
        """async function uploadFile(file: File, documentType: string): Promise<UploadedDocument> {\n  const presign = await $fetch('/api/registration/upload', { method: 'POST' })\n  await fetch(presign.upload_url, {\n    method: 'PUT',\n    body: file,\n    headers: { 'Content-Type': file.type },\n  })\n  return presign.file_id\n}\n\nasync function submit() {}\n""",
    )

    candidates = find_legacy_upload_candidates(str(tmp_path))
    assert len(candidates) == 1
    assert candidates[0].confirm_path == "/api/registration/upload/confirm"

    changed = migrate_legacy_upload_candidate(str(tmp_path), candidates[0])
    assert route in changed
    assert client in changed
    assert "content_base64" in (tmp_path / client).read_text(encoding="utf-8")
    assert "application-files" in (tmp_path / route).read_text(encoding="utf-8")

    assert find_legacy_upload_candidates(str(tmp_path)) == []


def test_skips_route_without_bucket_or_with_confirm(tmp_path: Path):
    _write(
        tmp_path,
        "server/api/upload.post.ts",
        """const presign = await fetch('/presign')\nawait fetch(presign.upload_url, {})\n""",
    )
    _write(tmp_path, "composables/useUpload.ts", "const x = '/api/upload'\n")
    assert find_legacy_upload_candidates(str(tmp_path)) == []
