package de.effigenix.infrastructure.production.web;

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

import java.time.LocalDate;
import java.util.Set;
import java.util.UUID;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@DisplayName("StartBatch Integration Tests")
class StartBatchIntegrationTest extends AbstractIntegrationTest {

    private String adminToken;
    private String viewerToken;

    private static final LocalDate PRODUCTION_DATE = LocalDate.of(2026, 3, 1);
    private static final LocalDate BEST_BEFORE_DATE = LocalDate.of(2026, 6, 1);

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

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

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

    @Nested
    @DisplayName("POST /api/production/batches/{id}/start – Produktion starten")
    class StartBatchEndpoint {

        @Test
        @DisplayName("PLANNED Charge starten → 200 mit IN_PRODUCTION Status")
        void startBatch_withPlannedBatch_returns200() throws Exception {
            String batchId = createPlannedBatch();

            mockMvc.perform(post("/api/production/batches/{id}/start", batchId)
                            .header("Authorization", "Bearer " + adminToken))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.id").value(batchId))
                    .andExpect(jsonPath("$.status").value("IN_PRODUCTION"))
                    .andExpect(jsonPath("$.consumptions").isArray())
                    .andExpect(jsonPath("$.consumptions").isEmpty());
        }

        @Test
        @DisplayName("Bereits gestartete Charge → 409")
        void startBatch_alreadyInProduction_returns409() throws Exception {
            String batchId = createPlannedBatch();

            // Start once
            mockMvc.perform(post("/api/production/batches/{id}/start", batchId)
                            .header("Authorization", "Bearer " + adminToken))
                    .andExpect(status().isOk());

            // Start again
            mockMvc.perform(post("/api/production/batches/{id}/start", batchId)
                            .header("Authorization", "Bearer " + adminToken))
                    .andExpect(status().isConflict())
                    .andExpect(jsonPath("$.code").value("BATCH_INVALID_STATUS_TRANSITION"));
        }

        @Test
        @DisplayName("Charge nicht gefunden → 404")
        void startBatch_notFound_returns404() throws Exception {
            mockMvc.perform(post("/api/production/batches/{id}/start", UUID.randomUUID().toString())
                            .header("Authorization", "Bearer " + adminToken))
                    .andExpect(status().isNotFound())
                    .andExpect(jsonPath("$.code").value("BATCH_NOT_FOUND"));
        }
    }

    @Nested
    @DisplayName("Authorization")
    class AuthTests {

        @Test
        @DisplayName("Ohne BATCH_WRITE → 403")
        void startBatch_withViewerToken_returns403() throws Exception {
            mockMvc.perform(post("/api/production/batches/{id}/start", UUID.randomUUID().toString())
                            .header("Authorization", "Bearer " + viewerToken))
                    .andExpect(status().isForbidden());
        }

        @Test
        @DisplayName("Ohne Token → 401")
        void startBatch_withoutToken_returns401() throws Exception {
            mockMvc.perform(post("/api/production/batches/{id}/start", UUID.randomUUID().toString()))
                    .andExpect(status().isUnauthorized());
        }
    }

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

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

        var request = new PlanBatchRequest(
                recipeId, "100", "KILOGRAM", PRODUCTION_DATE, BEST_BEFORE_DATE);

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

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

    private String createActiveRecipe() throws Exception {
        String json = """
                {
                    "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(json))
                .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;
    }
}
