import providers.gpt_image as gi


def test_missing_key_reports_failed(monkeypatch):
    monkeypatch.delenv("OPENAI_API_KEY", raising=False)
    calls = []
    monkeypatch.setattr(gi, "webhook_update_task", lambda *a, **k: calls.append((a, k)))
    gi.run_gpt_image_generation("t1", {"prompt": "a cat"})
    # 마지막 호출이 failed
    assert calls[-1][0][1] == "failed"


def test_success_saves_and_reports_url(monkeypatch):
    monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
    calls = []
    monkeypatch.setattr(gi, "webhook_update_task", lambda *a, **k: calls.append((a, k)))
    monkeypatch.setattr(gi, "save_b64_png", lambda tid, b64: "/media/image/t1.png")

    class FakeResp:
        status_code = 200

        def json(self):
            return {"data": [{"b64_json": "ZmFrZQ=="}]}

        def raise_for_status(self):
            pass

    monkeypatch.setattr(gi.requests, "post", lambda *a, **k: FakeResp())

    gi.run_gpt_image_generation("t1", {"prompt": "a cat"})
    succeeded = [c for c in calls if c[0][1] == "succeeded"]
    assert succeeded and succeeded[-1][1]["image_url"] == "/media/image/t1.png"
