# backend/tests/test_connector_routes.py — 라우터 + 로컬 우선 임포트(C10 CSV / C11 ics / C12 disconnect)
# phase-16+: 메일/일정 mock 계정 시드 제거 → 해당 테스트는 계정을 직접 생성.
import pytest

from app.config import get_settings
from app.models import ConnectorAccount, ConnectorDomain, ConnState


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


def test_ics_import_calendar(client, session, monkeypatch):
    # C11: .ics → event (OAuth 불필요). 일정 계정을 직접 생성.
    s, _ = session
    s.add(ConnectorAccount(id="ca-cal-google", domain=ConnectorDomain.calendar,
                           provider="google_calendar", name="Google 캘린더"))
    s.commit()
    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_disconnect_purges_token(client, session):
    # C12: 해제 → 토큰 폐기 + state disconnected. 연결된 메일 계정을 직접 생성.
    s, _ = session
    s.add(ConnectorAccount(id="ca-mail-work", domain=ConnectorDomain.mail, provider="gmail",
                           state=ConnState.connected, external_account_id="me@gmail.com",
                           token_enc="enc", name="me@gmail.com"))
    s.commit()
    r = client.post("/api/connectors/ca-mail-work/disconnect").json()
    assert r["state"] == "disconnected" and r["on"] is False and r["last"] == "연결 안 됨"


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
