/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

import io.ktor.http.*
import org.junit.Test
import tech.libeufin.common.*
import kotlin.test.*

class ParamsTest {
    @Test
    fun parse() {
        fun String.check(timeout_ms: Long, limit: Int, offset: Long) {
            val parameters = this.parseUrlEncodedParameters()
            val parsed = HistoryParams.extract(parameters)
            assertEquals(HistoryParams(PageParams(limit, offset), PollingParams(timeout_ms)), parsed)
        }
        fun String.fail(msg: String) {
            val parameters = this.parseUrlEncodedParameters()
            val e = assertFailsWith<ApiException> {
                HistoryParams.extract(parameters)
            }
            assertEquals(HttpStatusCode.BadRequest, e.httpStatus)
            assertEquals(msg, e.message)
        }
        sequenceOf(
            "long_poll_ms=1&delta=2&offset=3",
            "timeout_ms=1&limit=2&start=3",
            "long_poll_ms=1&delta=2&offset=3&timeout_ms=1&limit=2&start=3"
        ).forEach { case -> case.check(1, 2, 3) }
        "".check(0, -20, Long.MAX_VALUE)
        "limit=1".check(0, 1, 0)
        "limit=${MAX_PAGE_SIZE}".check(0, MAX_PAGE_SIZE, 0)
        "limit=0".fail("Param 'limit' must be non-zero")
        "limit=${MAX_PAGE_SIZE+1}".fail("Param 'limit' must be <= ${MAX_PAGE_SIZE}")
        "limit=${-MAX_PAGE_SIZE}".check(0, -MAX_PAGE_SIZE, Long.MAX_VALUE)
        "limit=${-MAX_PAGE_SIZE-1}".fail("Param 'limit' must be >= ${-MAX_PAGE_SIZE}")
        "limit=${Int.MIN_VALUE}".fail("Param 'limit' must be >= ${-MAX_PAGE_SIZE}")
        "offset=-1".fail("Param 'offset' must be a positive number")
        "long_poll_ms=${MAX_TIMEOUT_MS+1}&limit=10".check(MAX_TIMEOUT_MS, 10, 0)
        "long_poll_ms=1&timeout_ms=2".fail("Param 'timeout_ms' cannot be used with param 'long_poll_ms'")
        "limit=1&delta=2".fail("Param 'limit' cannot be used with param 'delta'")
        "offset=1&start=2".fail("Param 'offset' cannot be used with param 'start'")
    }
}