"""S4.7 / package 1: characterization of the two foreign_offers reads behind the refresh routes (id lookup, active TripInvest list).

Passing on the OLD code; must pass unchanged after the two SELECTs move into `foreign_offers_store`.
"""
import sqlite3

import pytest

import InvestmentManager.routes.foreign_offers as routes
from tests.investmentmanager.test_foreign_developments_routes import _login, foreign_db  # noqa: F401
from tests.investmentmanager.test_foreign_offer_refresh_guard import (  # noqa: F401
    _connect, _insert_offer, refresh_db, admin, _spy_tripinvest_importer)


def add(db, *rows):
    conn = _connect(db)
    try:
        for offer_id, platform, url, active in rows:
            _insert_offer(conn, offer_id, platform, url, active=active)
        conn.commit()
    finally:
        conn.close()


def test_refresh_of_an_unknown_offer_is_404(admin, monkeypatch):
    calls = _spy_tripinvest_importer(monkeypatch)
    response = admin.post('/crm/foreign-offers/refresh/999')
    assert response.status_code == 404 and response.get_json() == {'error': 'Nie znaleziono oferty do odświeżenia.'} and calls == []


def test_refresh_of_an_offer_without_a_source_url_is_404(admin, refresh_db, monkeypatch):
    add(refresh_db, (13, 'tripinvest', '', True))
    calls = _spy_tripinvest_importer(monkeypatch)
    response = admin.post('/crm/foreign-offers/refresh/13')
    assert response.status_code == 404 and response.get_json()['error'] == 'Nie znaleziono oferty do odświeżenia.' and calls == []


def test_refresh_uses_the_stripped_url_of_the_row_even_when_the_offer_is_inactive(admin, refresh_db, monkeypatch):
    add(refresh_db, (14, 'tripinvest', '  https://tripinvest.pl/oferta/padded-14  ', False))
    calls = _spy_tripinvest_importer(monkeypatch)
    response = admin.post('/crm/foreign-offers/refresh/14')
    assert response.status_code == 200 and calls == ['https://tripinvest.pl/oferta/padded-14']


def test_refresh_all_runs_active_tripinvest_rows_in_id_order_and_reports_each_failure(admin, refresh_db, monkeypatch):
    add(refresh_db, (20, 'tripinvest', 'https://tripinvest.pl/oferta/twenty', True), (15, 'tripinvest', 'https://tripinvest.pl/oferta/fifteen', True),
        (17, 'tripinvest', '', True), (18, 'tripinvest', 'https://tripinvest.pl/oferta/bad-value', True),
        (19, 'tripinvest', 'https://tripinvest.pl/oferta/boom', True), (21, 'tripinvest', 'https://tripinvest.pl/oferta/off', False))
    calls = []

    def fake(url):
        calls.append(url)
        if url.endswith('bad-value'):
            raise ValueError('the page has no offer content')
        if url.endswith('boom'):
            raise RuntimeError('secret internals /home/x')
        return {'source_url': url}
    monkeypatch.setattr(routes, 'upsert_foreign_offer_from_tripinvest', fake)
    response = admin.post('/crm/foreign-offers/refresh-all')
    body = response.get_json()
    assert response.status_code == 200 and calls == ['https://tripinvest.pl/oferta/offer-1', 'https://tripinvest.pl/oferta/fifteen',
                                                       'https://tripinvest.pl/oferta/bad-value', 'https://tripinvest.pl/oferta/boom',
                                                       'https://tripinvest.pl/oferta/twenty']          # ids 1, 15, 18, 19, 20 (17 has no url, 5 and 21 inactive)
    assert body['ok'] is False and body['total_count'] == 6 and body['refreshed_count'] == 3 and body['error_count'] == 3
    assert [r['source_url'] for r in body['results']] == ['https://tripinvest.pl/oferta/offer-1', 'https://tripinvest.pl/oferta/fifteen',
                                                          'https://tripinvest.pl/oferta/twenty']
    errors = {e['id']: e for e in body['errors']}
    assert list(errors) == [17, 18, 19] and errors[17] == {'id': 17, 'error': 'Brak source_url.'}
    assert errors[18] == {'id': 18, 'error': 'the page has no offer content'}
    assert errors[19]['error'] == 'Nie udało się odświeżyć oferty.' and 'request_id' in errors[19] and 'secret' not in str(body)


def test_refresh_all_with_no_matching_rows(admin, refresh_db, monkeypatch):
    conn = _connect(refresh_db)
    conn.execute("UPDATE foreign_offers SET is_active = 0")
    conn.commit()
    conn.close()
    calls = _spy_tripinvest_importer(monkeypatch)
    body = admin.post('/crm/foreign-offers/refresh-all').get_json()
    assert calls == [] and body == {'ok': True, 'results': [], 'errors': [], 'refreshed_count': 0, 'error_count': 0, 'total_count': 0}


@pytest.mark.parametrize('path', ['/crm/foreign-offers/refresh/1', '/crm/foreign-offers/refresh-all'])
def test_permissions_are_unchanged(client, refresh_db, monkeypatch, path):
    calls = _spy_tripinvest_importer(monkeypatch)
    _login(client, 'agent')
    response = client.post(path)
    assert response.status_code == 403 and calls == []
