require "test_helper"

class ApiEntriesTest < ActionDispatch::IntegrationTest
  test "returns active entries with language fields" do
    entry = entries(:one)

    get "/api/entries"

    assert_response :success
    payload = JSON.parse(response.body)
    entry_payload = payload.find { |item| item["id"] == entry.id }

    assert_not_nil entry_payload
    assert_equal entry.fi, entry_payload["fi"]
    assert_equal entry.en, entry_payload["en"]
    assert_equal entry.sv, entry_payload["sv"]
    assert_equal entry.no, entry_payload["no"]
    assert_equal entry.ru, entry_payload["ru"]
    assert_equal entry.de, entry_payload["de"]
  end

  test "filters by updated_at when since param is provided" do
    older_entry = Entry.create!(
      fi: "Older Entry",
      category: :word,
      status: :active
    )
    older_entry.update_column(:updated_at, 2.days.ago)

    newer_entry = Entry.create!(
      fi: "Newer Entry",
      category: :word,
      status: :active
    )
    newer_entry.update_column(:updated_at, 1.hour.ago)

    get "/api/entries", params: { since: 1.day.ago.iso8601 }

    assert_response :success
    payload = JSON.parse(response.body)
    returned_ids = payload.map { |item| item["id"] }

    assert_includes returned_ids, newer_entry.id
    assert_not_includes returned_ids, older_entry.id
  end

  test "returns bad request for invalid since param" do
    get "/api/entries", params: { since: "not-a-time" }

    assert_response :bad_request
    payload = JSON.parse(response.body)
    assert_equal "Invalid since parameter. Use ISO8601 timestamp.", payload["error"]
  end

  test "exposes swagger docs" do
    get "/api/swagger"

    assert_response :success
    payload = JSON.parse(response.body)
    assert_equal "Sanasto Wiki API", payload.dig("info", "title")
    assert_includes payload.keys, "paths"
  end
end
