package de.effigenix.infrastructure.production.web;

import de.effigenix.domain.usermanagement.RoleName;
import de.effigenix.infrastructure.AbstractIntegrationTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;

import java.util.Set;

import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@DisplayName("ListRecipes Integration Tests")
class ListRecipesIntegrationTest extends AbstractIntegrationTest {

    private String adminToken;
    private String viewerToken;

    @BeforeEach
    void setUp() {
        String adminRoleId = createRole(RoleName.ADMIN, "Admin");
        String viewerRoleId = createRole(RoleName.PRODUCTION_WORKER, "Viewer");

        String adminId = createUser("recipe.admin", "recipe.admin@test.com", Set.of(adminRoleId), "BRANCH-01");
        String viewerId = createUser("recipe.viewer", "recipe.viewer@test.com", Set.of(viewerRoleId), "BRANCH-01");

        adminToken = generateToken(adminId, "recipe.admin", "RECIPE_WRITE,RECIPE_READ");
        viewerToken = generateToken(viewerId, "recipe.viewer", "USER_READ");
    }

    @Test
    @DisplayName("Alle Rezepte auflisten → 200 mit Summary-Format")
    void listRecipes_returnsAllWithSummaryFormat() throws Exception {
        createRecipe("Bratwurst", 1);
        createRecipe("Leberwurst", 1);

        mockMvc.perform(get("/api/recipes")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].ingredientCount").isNumber())
                .andExpect(jsonPath("$[0].stepCount").isNumber())
                .andExpect(jsonPath("$[0].ingredients").doesNotExist())
                .andExpect(jsonPath("$[0].productionSteps").doesNotExist());
    }

    @Test
    @DisplayName("Rezepte nach Status filtern → 200 nur passende")
    void listRecipes_filteredByStatus_returnsOnlyMatching() throws Exception {
        String recipeId = createRecipe("Bratwurst", 1);
        createRecipe("Leberwurst", 1);

        // Zutat hinzufügen und aktivieren
        addIngredient(recipeId);
        activateRecipe(recipeId);

        mockMvc.perform(get("/api/recipes")
                        .param("status", "ACTIVE")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0].name").value("Bratwurst"))
                .andExpect(jsonPath("$[0].status").value("ACTIVE"));
    }

    @Test
    @DisplayName("Ungültiger Status-Parameter → 400")
    void listRecipes_invalidStatus_returns400() throws Exception {
        mockMvc.perform(get("/api/recipes")
                        .param("status", "INVALID")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.code").value("RECIPE_VALIDATION_ERROR"));
    }

    @Test
    @DisplayName("Leere Liste → 200 mit leerem Array")
    void listRecipes_empty_returns200WithEmptyArray() throws Exception {
        mockMvc.perform(get("/api/recipes")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(0)));
    }

    @Test
    @DisplayName("Rezepte auflisten ohne RECIPE_READ → 403")
    void listRecipes_withoutPermission_returns403() throws Exception {
        mockMvc.perform(get("/api/recipes")
                        .header("Authorization", "Bearer " + viewerToken))
                .andExpect(status().isForbidden());
    }

    @Test
    @DisplayName("Rezepte auflisten ohne Token → 401")
    void listRecipes_withoutToken_returns401() throws Exception {
        mockMvc.perform(get("/api/recipes"))
                .andExpect(status().isUnauthorized());
    }

    private String createRecipe(String name, int version) throws Exception {
        String json = """
                {
                    "name": "%s",
                    "version": %d,
                    "type": "FINISHED_PRODUCT",
                    "description": "Testrezept",
                    "yieldPercentage": 85,
                    "shelfLifeDays": 14,
                    "outputQuantity": "100",
                    "outputUom": "KILOGRAM",
                    "articleId": "article-123"
                }
                """.formatted(name, version);

        var result = mockMvc.perform(post("/api/recipes")
                        .header("Authorization", "Bearer " + adminToken)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(json))
                .andExpect(status().isCreated())
                .andReturn();

        return objectMapper.readTree(result.getResponse().getContentAsString()).get("id").asText();
    }

    private void addIngredient(String recipeId) throws Exception {
        String json = """
                {
                    "position": 1,
                    "articleId": "article-123",
                    "quantity": "5.5",
                    "uom": "KILOGRAM",
                    "substitutable": false
                }
                """;

        mockMvc.perform(post("/api/recipes/{id}/ingredients", recipeId)
                        .header("Authorization", "Bearer " + adminToken)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(json))
                .andExpect(status().isCreated());
    }

    private void activateRecipe(String recipeId) throws Exception {
        mockMvc.perform(post("/api/recipes/{id}/activate", recipeId)
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk());
    }
}
