package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.jpa.maven.Version;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.restassured.RestAssured;
import jakarta.inject.Inject;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.InputStream;
import java.util.Optional;

@QuarkusTest
public class ResourceTest
{
    @Inject
    Flyway flyway;

    @Inject
    VersionService versionService;

    @BeforeEach
    void before()
    {
        flyway.clean();
        flyway.migrate();
    }

    @Test
    @TestSecurity(user = "user")
    void test()
    {
        RestAssured.given().body(readFile("/jar/postgresql-42.7.9.jar")).put("/maven2/org/postgresql/postgresql/42.7.9/postgresql-42.7.9.jar");
        RestAssured.given().body(readFile("/jar/postgresql-42.7.9.pom")).put("/maven2/org/postgresql/postgresql/42.7.9/postgresql-42.7.9.pom");
        byte[] responseJar = RestAssured.given().get("/maven2/org/postgresql/postgresql/42.7.9/postgresql-42.7.9.jar").getBody().asByteArray();
        String responsePom = RestAssured.given().get("/maven2/org/postgresql/postgresql/42.7.9/postgresql-42.7.9.pom").getBody().asString();
        String responsePomMd5 = RestAssured.given().get("/maven2/org/postgresql/postgresql/42.7.9/postgresql-42.7.9.pom.md5").getBody().asString();

        Optional<Version> version = versionService.findOptional("org.postgresql", "postgresql", "42.7.9");

        Assertions.assertTrue(version.isPresent());
        Assertions.assertTrue(responseJar.length > 0);
        Assertions.assertTrue(responsePom !=null && responsePom.startsWith("<?xml"));
        Assertions.assertEquals("a6b97b8d22c55f296040344dd75641b2", responsePomMd5);
    }

    @Test
    @TestSecurity(user = "user")
    void test_snapshot()
    {
        RestAssured.given().body(readFile("/jar/postgresql-42.7.9.jar")).put("/maven2/org/postgresql/postgresql/42.7.9-SNAPSHOT/postgresql-42.7.9.jar").then().statusCode(501);
        RestAssured.given().body(readFile("/jar/postgresql-42.7.9.pom")).put("/maven2/org/postgresql/postgresql/42.7.9-SNAPSHOT/postgresql-42.7.9.pom").then().statusCode(501);
    }

    private InputStream readFile(String path)
    {
        return getClass().getResourceAsStream(path);
    }
}
