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 java.util.UUID;

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("GetBatch Integration Tests")
class GetBatchIntegrationTest 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("batch.admin", "batch.admin@test.com", Set.of(adminRoleId), "BRANCH-01");
        String viewerId = createUser("batch.viewer", "batch.viewer@test.com", Set.of(viewerRoleId), "BRANCH-01");

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

    @Test
    @DisplayName("Batch per ID abrufen → 200 mit vollständigen Daten")
    void getBatch_existingId_returns200WithFullDetails() throws Exception {
        String batchId = createBatch();

        mockMvc.perform(get("/api/production/batches/{id}", batchId)
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id").value(batchId))
                .andExpect(jsonPath("$.batchNumber").isNotEmpty())
                .andExpect(jsonPath("$.recipeId").isNotEmpty())
                .andExpect(jsonPath("$.status").value("PLANNED"))
                .andExpect(jsonPath("$.plannedQuantity").isNotEmpty())
                .andExpect(jsonPath("$.plannedQuantityUnit").value("KILOGRAM"))
                .andExpect(jsonPath("$.productionDate").value("2026-03-01"))
                .andExpect(jsonPath("$.bestBeforeDate").value("2026-06-01"));
    }

    @Test
    @DisplayName("Nicht existierender Batch → 404")
    void getBatch_nonExistentId_returns404() throws Exception {
        mockMvc.perform(get("/api/production/batches/{id}", "nonexistent-id")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isNotFound())
                .andExpect(jsonPath("$.code").value("BATCH_NOT_FOUND"));
    }

    @Test
    @DisplayName("Batch abrufen ohne BATCH_READ → 403")
    void getBatch_withoutPermission_returns403() throws Exception {
        mockMvc.perform(get("/api/production/batches/{id}", "any-id")
                        .header("Authorization", "Bearer " + viewerToken))
                .andExpect(status().isForbidden());
    }

    @Test
    @DisplayName("Batch abrufen ohne Token → 401")
    void getBatch_withoutToken_returns401() throws Exception {
        mockMvc.perform(get("/api/production/batches/{id}", "any-id"))
                .andExpect(status().isUnauthorized());
    }

    @Test
    @DisplayName("Batch per Number abrufen → 200")
    void findByNumber_existingNumber_returns200() throws Exception {
        createBatch();

        mockMvc.perform(get("/api/production/batches/by-number/{batchNumber}", "P-2026-03-01-001")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.batchNumber").value("P-2026-03-01-001"))
                .andExpect(jsonPath("$.status").value("PLANNED"));
    }

    @Test
    @DisplayName("Nicht existierende BatchNumber → 404")
    void findByNumber_nonExistent_returns404() throws Exception {
        mockMvc.perform(get("/api/production/batches/by-number/{batchNumber}", "P-2099-01-01-999")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isNotFound())
                .andExpect(jsonPath("$.code").value("BATCH_NOT_FOUND_BY_NUMBER"));
    }

    @Test
    @DisplayName("BatchNumber-Suche ohne BATCH_READ → 403")
    void findByNumber_withoutPermission_returns403() throws Exception {
        mockMvc.perform(get("/api/production/batches/by-number/{batchNumber}", "P-2026-03-01-001")
                        .header("Authorization", "Bearer " + viewerToken))
                .andExpect(status().isForbidden());
    }

    @Test
    @DisplayName("BatchNumber-Suche ohne Token → 401")
    void findByNumber_withoutToken_returns401() throws Exception {
        mockMvc.perform(get("/api/production/batches/by-number/{batchNumber}", "P-2026-03-01-001"))
                .andExpect(status().isUnauthorized());
    }

    @Test
    @DisplayName("Ungültiges BatchNumber-Format → 400")
    void findByNumber_invalidFormat_returns400() throws Exception {
        mockMvc.perform(get("/api/production/batches/by-number/{batchNumber}", "INVALID-FORMAT")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.code").value("BATCH_VALIDATION_ERROR"));
    }

    // ==================== Hilfsmethoden ====================

    private String createBatch() throws Exception {
        String recipeId = createActiveRecipe();

        String json = """
                {
                    "recipeId": "%s",
                    "plannedQuantity": "100",
                    "plannedQuantityUnit": "KILOGRAM",
                    "productionDate": "2026-03-01",
                    "bestBeforeDate": "2026-06-01"
                }
                """.formatted(recipeId);

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

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

    private String createActiveRecipe() throws Exception {
        String recipeJson = """
                {
                    "name": "Test-Rezept-%s",
                    "version": 1,
                    "type": "FINISHED_PRODUCT",
                    "description": "Testrezept",
                    "yieldPercentage": 85,
                    "shelfLifeDays": 14,
                    "outputQuantity": "100",
                    "outputUom": "KILOGRAM",
                    "articleId": "article-123"
                }
                """.formatted(UUID.randomUUID().toString().substring(0, 8));

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

        String recipeId = objectMapper.readTree(result.getResponse().getContentAsString()).get("id").asText();

        String ingredientJson = """
                {"position": 1, "articleId": "%s", "quantity": "5.5", "uom": "KILOGRAM", "substitutable": false}
                """.formatted(UUID.randomUUID().toString());

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

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

        return recipeId;
    }
}
