"""image_asset.file_path CHECK constraint PG 환경 검증 (Phase 3 follow-up G1).

SQLite in-memory 검증 (tests/core/test_file_paths.py) 외에 PG 환경에서도
``NOT LIKE '/%'`` CHECK 가 동일하게 작동하는지 회귀 가드. 운영 DB 와 동일한
PG dialect 에서 실 INSERT/UPDATE 차단을 직접 확인.

Lane: ``-m pg`` 명시 시만 실행. 기본 SQLite lane 에서는 skip.
"""
from __future__ import annotations

import uuid

import pytest
from sqlalchemy import text as sql_text
from sqlalchemy.exc import IntegrityError

pytestmark = pytest.mark.pg


def _seed_project(session, pid: str) -> None:
    """FK 의존 — project_registry row 시드 (UserAccount 도 FK 인지 따라).

    project_registry.created_by 가 user_account.id 를 참조하지만 nullable=True
    가능. 기본 NOT NULL 일 가능성 → user_account 도 시드.
    """
    uid = f"test-pg-check-{uuid.uuid4()}"
    session.execute(sql_text(
        "INSERT INTO user_account (id, username, display_name, password_hash, "
        "role, is_active, created_at, updated_at) VALUES "
        "(:uid, :uname, 't', 'x', 'creator', 1, '2026-01-01', '2026-01-01')"
    ), {"uid": uid, "uname": f"u_{uid}"})
    session.execute(sql_text(
        "INSERT INTO project_registry (id, name, created_by, created_at, updated_at) "
        "VALUES (:pid, 'pg-check', :uid, '2026-01-01', '2026-01-01')"
    ), {"pid": pid, "uid": uid})
    session.commit()


def test_check_rejects_absolute_path_pg(pg_session):
    """PG 환경에서 절대 경로 raw INSERT 가 CHECK 위반으로 거부."""
    pid = f"pg-check-{uuid.uuid4()}"
    _seed_project(pg_session, pid)

    aid = str(uuid.uuid4())
    with pytest.raises(IntegrityError):
        pg_session.execute(sql_text(
            "INSERT INTO image_asset (id, project_id, asset_type, file_path, "
            "status, variant_index, variant_label, created_at) VALUES "
            "(:id, :pid, 'reference', '/abs/blocked.png', 'generated', 0, 'v00', '2026-01-01')"
        ), {"id": aid, "pid": pid})
        pg_session.commit()
    pg_session.rollback()


def test_check_allows_relative_path_pg(pg_session):
    """PG 환경에서 상대 경로 raw INSERT 정상 통과."""
    pid = f"pg-check-{uuid.uuid4()}"
    _seed_project(pg_session, pid)

    aid = str(uuid.uuid4())
    pg_session.execute(sql_text(
        "INSERT INTO image_asset (id, project_id, asset_type, file_path, "
        "status, variant_index, variant_label, created_at) VALUES "
        "(:id, :pid, 'reference', 'projects/p1/img.png', 'generated', 0, 'v00', '2026-01-01')"
    ), {"id": aid, "pid": pid})
    pg_session.commit()

    raw = pg_session.execute(
        sql_text("SELECT file_path FROM image_asset WHERE id = :id"),
        {"id": aid},
    ).scalar()
    assert raw == "projects/p1/img.png"


def test_check_rejects_update_to_absolute_pg(pg_session):
    """PG 환경에서 raw UPDATE 로 절대 경로 변경 시도 IntegrityError 거부."""
    pid = f"pg-check-{uuid.uuid4()}"
    _seed_project(pg_session, pid)

    aid = str(uuid.uuid4())
    pg_session.execute(sql_text(
        "INSERT INTO image_asset (id, project_id, asset_type, file_path, "
        "status, variant_index, variant_label, created_at) VALUES "
        "(:id, :pid, 'reference', 'projects/p1/img.png', 'generated', 0, 'v00', '2026-01-01')"
    ), {"id": aid, "pid": pid})
    pg_session.commit()

    with pytest.raises(IntegrityError):
        pg_session.execute(
            sql_text("UPDATE image_asset SET file_path = '/abs/path.png' WHERE id = :id"),
            {"id": aid},
        )
        pg_session.commit()
    pg_session.rollback()


def test_check_allows_empty_file_path_pg(pg_session):
    """PG 환경에서 빈 문자열 file_path 도 허용 (placeholder 시나리오)."""
    pid = f"pg-check-{uuid.uuid4()}"
    _seed_project(pg_session, pid)

    aid = str(uuid.uuid4())
    pg_session.execute(sql_text(
        "INSERT INTO image_asset (id, project_id, asset_type, file_path, "
        "status, variant_index, variant_label, created_at) VALUES "
        "(:id, :pid, 'reference', '', 'generated', 0, 'v00', '2026-01-01')"
    ), {"id": aid, "pid": pid})
    pg_session.commit()
