"""Unified Create Job + JD validate (?action= query)."""

from __future__ import annotations

import pytest
from fastapi.testclient import TestClient

from app.config import get_settings
from app.database import ensure_schema
from app.main import app

client = TestClient(app)
HEADERS = {
    "X-Internal-Token": get_settings().internal_api_token,
    "X-Company-Id": "co-test-001",
    "X-User-Id": "user-test-001",
}


@pytest.fixture(autouse=True)
def _schema(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr("app.llm._provider_available", lambda _name: False)
    ensure_schema()
    yield


def test_jobs_draft_validate_publish_flow() -> None:
    draft = client.post(
        "/api/v1/jobs?action=draft",
        headers=HEADERS,
        json={
            "role_title": "Backend Engineer",
            "employment_type": "full_time",
            "location": "Remote - India",
            "years_of_experience": "3-5",
            "skills": ["Python", "FastAPI", "PostgreSQL"],
            "company_context": "Product SaaS platform team",
            "salary_range": "1200000-1800000",
            "currency": "INR",
            "openings": 2,
        },
    )
    assert draft.status_code == 200, draft.text
    body = draft.json()
    assert body["action"] == "draft"
    assert body["job_id"]
    assert body["markdown"]
    assert body["sections"]["responsibilities"]
    assert body["salary_range"] == "1200000-1800000"
    assert body["currency"] == "INR"
    assert body["openings"] == 2
    job_id = body["job_id"]

    validate = client.post(
        f"/api/v1/jobs?action=validate",
        headers=HEADERS,
        json={"job_id": job_id},
    )
    assert validate.status_code == 200, validate.text
    assert "validation" in validate.json()

    publish = client.post(
        "/api/v1/jobs?action=publish",
        headers=HEADERS,
        json={
            "job_id": job_id,
            "options": {"force_publish": True, "platform_job_id": "plat-job-001"},
        },
    )
    assert publish.status_code == 200, publish.text
    assert publish.json()["status_label"] == "published"
    assert publish.json()["platform_job_id"] == "plat-job-001"


def test_jobs_validate_action() -> None:
    res = client.post(
        "/api/v1/jobs?action=validate",
        headers=HEADERS,
        json={
            "role_title": "Engineer",
            "job_description": "We need a rockstar ninja. No responsibilities listed.",
        },
    )
    assert res.status_code == 200
    v = res.json()["validation"]
    assert "issues" in v


def test_draft_requires_role_title() -> None:
    res = client.post(
        "/api/v1/jobs?action=draft",
        headers=HEADERS,
        json={"skills": ["Python"]},
    )
    assert res.status_code == 422


def test_publish_requires_job_id() -> None:
    res = client.post(
        "/api/v1/jobs?action=publish",
        headers=HEADERS,
        json={},
    )
    assert res.status_code == 422


def test_action_query_required() -> None:
    res = client.post(
        "/api/v1/jobs",
        headers=HEADERS,
        json={"role_title": "Engineer"},
    )
    assert res.status_code == 422


def test_openapi_has_per_action_body_schemas() -> None:
    schema = app.openapi()
    components = schema["components"]["schemas"]
    for name in ("JobDraftBody", "JobRewriteBody", "JobValidateBody", "JobPublishBody"):
        assert name in components, name
    post = schema["paths"]["/api/v1/jobs"]["post"]
    params = {p["name"] for p in post.get("parameters") or [] if p.get("in") == "query"}
    assert "action" in params
    one_of = post["requestBody"]["content"]["application/json"]["schema"]["oneOf"]
    refs = {item["$ref"] for item in one_of}
    assert "#/components/schemas/JobDraftBody" in refs
    examples = post["requestBody"]["content"]["application/json"]["examples"]
    assert set(examples) >= {"draft", "rewrite", "validate", "publish"}
    # Bodies must not require action in JSON
    assert "action" not in examples["draft"]["value"]
