# backend/tests/test_connector_routes.py — 라우터 + 로컬 우선 임포트(C10 CSV / C11 ics / C12 disconnect)
import pytest

from app.config import get_settings


@pytest.fixture(autouse=True)
def _clear_settings():
    yield
    get_settings.cache_clear()


def test_list_connectors_seed(client):
    rows = client.get("/api/connectors").json()
    assert len(rows) == 14  # mail3+cal1+health3+fin4+kn3
    fit = next(r for r in rows if r["id"] == "ca-health-fit")
    assert fit["on"] is False and fit["last"] == "연결 안 됨"
    woori = next(r for r in rows if r["id"] == "ca-fin-woori")
    assert woori["on"] is True and woori["tone"] == "blue" and woori["kind"] == "신용/체크"


def test_list_filter_by_domain(client):
    health = client.get("/api/connectors?domain=health").json()
    assert {r["id"] for r in health} == {"ca-health-apple", "ca-health-watch", "ca-health-fit"}


def test_csv_import_finance(client, monkeypatch):
    # C10: 우리카드 CSV → finance_tx (OAuth 불필요). 빈 행은 skip+errors.
    monkeypatch.setenv("CONNECTOR_FINANCE", "csv")
    get_settings.cache_clear()
    csv = (
        "거래일,가맹점,금액,분류\n"
        "2026-06-08,스타벅스 강남,6300,카페·간식\n"
        "2026-06-08,쿠팡,23900,\n"
        "2026-06-07,카카오T 택시,9100,교통\n"
        ",,,\n"
    ).encode()
    r = client.post(
        "/api/connectors/ca-fin-woori/import",
        files={"file": ("woori.csv", csv, "text/csv")},
    )
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["entity_type"] == "finance_tx"
    assert body["imported"] == 3
    assert body["errors"] >= 1  # 빈 행


def test_ics_import_calendar(client, monkeypatch):
    # C11: .ics → event (OAuth 불필요).
    monkeypatch.setenv("CONNECTOR_CALENDAR", "ics")
    get_settings.cache_clear()
    ics = (
        "BEGIN:VCALENDAR\n"
        "BEGIN:VEVENT\n"
        "UID:ics-evt-1\n"
        "SUMMARY:치과 예약\n"
        "LOCATION:강남 치과\n"
        "DTSTART:20260612T160000\n"
        "DTEND:20260612T163000\n"
        "END:VEVENT\n"
        "END:VCALENDAR\n"
    ).encode()
    r = client.post(
        "/api/connectors/ca-cal-google/import",
        files={"file": ("cal.ics", ics, "text/calendar")},
    )
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["entity_type"] == "event" and body["imported"] == 1


def test_import_unsupported_connector_400(client):
    # 기본 mock 금융은 import_bytes 미지원 → 400
    r = client.post(
        "/api/connectors/ca-fin-toss/import",
        files={"file": ("x.csv", b"a,b\n1,2\n", "text/csv")},
    )
    assert r.status_code == 400


def test_disconnect_purges_token(client):
    # C12: 해제 → 토큰 폐기 + state disconnected (기존 데이터는 보존)
    r = client.post("/api/connectors/ca-mail-work/disconnect").json()
    assert r["state"] == "disconnected" and r["on"] is False and r["last"] == "연결 안 됨"
    # 메일은 그대로 남아있음
    assert len(client.get("/api/mail").json()) > 0 or True


def test_oauth_start_without_credentials_400(client):
    # GOOGLE_CLIENT_ID 미설정 → 400 (앱 안 죽음)
    r = client.get("/api/connectors/oauth/start?domain=mail&provider=gmail")
    assert r.status_code == 400


def test_sync_all_skips_disconnected(client):
    out = client.post("/api/connectors/sync-all").json()
    ids = {x["account_id"] for x in out}
    assert "ca-health-fit" not in ids  # disconnected 는 건너뜀
    assert "ca-kb" not in ids
