package de.effigenix.infrastructure.masterdata.web.controller;

import de.effigenix.application.masterdata.productcategory.CreateProductCategory;
import de.effigenix.application.masterdata.productcategory.DeleteProductCategory;
import de.effigenix.application.masterdata.productcategory.ListProductCategories;
import de.effigenix.application.masterdata.productcategory.UpdateProductCategory;
import de.effigenix.application.masterdata.productcategory.command.CreateProductCategoryCommand;
import de.effigenix.application.masterdata.productcategory.command.UpdateProductCategoryCommand;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryError;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryId;
import de.effigenix.infrastructure.masterdata.web.dto.CreateProductCategoryRequest;
import de.effigenix.infrastructure.masterdata.web.dto.ProductCategoryResponse;
import de.effigenix.infrastructure.masterdata.web.dto.UpdateProductCategoryRequest;
import de.effigenix.shared.security.ActorId;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/categories")
@SecurityRequirement(name = "Bearer Authentication")
@Tag(name = "Product Categories", description = "Product category management endpoints")
public class ProductCategoryController {

    private static final Logger logger = LoggerFactory.getLogger(ProductCategoryController.class);

    private final CreateProductCategory createProductCategory;
    private final UpdateProductCategory updateProductCategory;
    private final ListProductCategories listProductCategories;
    private final DeleteProductCategory deleteProductCategory;

    public ProductCategoryController(
            CreateProductCategory createProductCategory,
            UpdateProductCategory updateProductCategory,
            ListProductCategories listProductCategories,
            DeleteProductCategory deleteProductCategory
    ) {
        this.createProductCategory = createProductCategory;
        this.updateProductCategory = updateProductCategory;
        this.listProductCategories = listProductCategories;
        this.deleteProductCategory = deleteProductCategory;
    }

    @PostMapping
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<ProductCategoryResponse> createCategory(
            @Valid @RequestBody CreateProductCategoryRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Creating product category: {} by actor: {}", request.name(), actorId.value());

        var cmd = new CreateProductCategoryCommand(request.name(), request.description());
        var result = createProductCategory.execute(cmd, actorId);

        if (result.isFailure()) {
            throw new ProductCategoryDomainErrorException(result.unsafeGetError());
        }

        logger.info("Product category created: {}", request.name());
        return ResponseEntity.status(HttpStatus.CREATED).body(ProductCategoryResponse.from(result.unsafeGetValue()));
    }

    @GetMapping
    public ResponseEntity<List<ProductCategoryResponse>> listCategories(Authentication authentication) {
        var actorId = extractActorId(authentication);
        logger.info("Listing product categories by actor: {}", actorId.value());

        var result = listProductCategories.execute();

        if (result.isFailure()) {
            throw new ProductCategoryDomainErrorException(result.unsafeGetError());
        }

        var response = result.unsafeGetValue().stream().map(ProductCategoryResponse::from).toList();
        return ResponseEntity.ok(response);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<ProductCategoryResponse> updateCategory(
            @PathVariable("id") String categoryId,
            @Valid @RequestBody UpdateProductCategoryRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Updating product category: {} by actor: {}", categoryId, actorId.value());

        var cmd = new UpdateProductCategoryCommand(categoryId, request.name(), request.description());
        var result = updateProductCategory.execute(cmd, actorId);

        if (result.isFailure()) {
            throw new ProductCategoryDomainErrorException(result.unsafeGetError());
        }

        logger.info("Product category updated: {}", categoryId);
        return ResponseEntity.ok(ProductCategoryResponse.from(result.unsafeGetValue()));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<Void> deleteCategory(
            @PathVariable("id") String categoryId,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Deleting product category: {} by actor: {}", categoryId, actorId.value());

        var result = deleteProductCategory.execute(ProductCategoryId.of(categoryId), actorId);

        if (result.isFailure()) {
            throw new ProductCategoryDomainErrorException(result.unsafeGetError());
        }

        logger.info("Product category deleted: {}", categoryId);
        return ResponseEntity.noContent().build();
    }

    private ActorId extractActorId(Authentication authentication) {
        if (authentication == null || authentication.getName() == null) {
            throw new IllegalStateException("No authentication found in SecurityContext");
        }
        return ActorId.of(authentication.getName());
    }

    public static class ProductCategoryDomainErrorException extends RuntimeException {
        private final ProductCategoryError error;

        public ProductCategoryDomainErrorException(ProductCategoryError error) {
            super(error.message());
            this.error = error;
        }

        public ProductCategoryError getError() {
            return error;
        }
    }
}
