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

import de.effigenix.application.masterdata.supplier.*;
import de.effigenix.application.masterdata.supplier.command.*;
import de.effigenix.domain.masterdata.supplier.Supplier;
import de.effigenix.domain.masterdata.supplier.SupplierError;
import de.effigenix.domain.masterdata.supplier.SupplierId;
import de.effigenix.domain.masterdata.supplier.SupplierStatus;
import de.effigenix.infrastructure.masterdata.web.dto.*;
import de.effigenix.shared.common.Result;
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/suppliers")
@SecurityRequirement(name = "Bearer Authentication")
@Tag(name = "Suppliers", description = "Supplier management endpoints")
public class SupplierController {

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

    private final CreateSupplier createSupplier;
    private final UpdateSupplier updateSupplier;
    private final GetSupplier getSupplier;
    private final ListSuppliers listSuppliers;
    private final ActivateSupplier activateSupplier;
    private final DeactivateSupplier deactivateSupplier;
    private final RateSupplier rateSupplier;
    private final AddCertificate addCertificate;
    private final RemoveCertificate removeCertificate;

    public SupplierController(
            CreateSupplier createSupplier,
            UpdateSupplier updateSupplier,
            GetSupplier getSupplier,
            ListSuppliers listSuppliers,
            ActivateSupplier activateSupplier,
            DeactivateSupplier deactivateSupplier,
            RateSupplier rateSupplier,
            AddCertificate addCertificate,
            RemoveCertificate removeCertificate
    ) {
        this.createSupplier = createSupplier;
        this.updateSupplier = updateSupplier;
        this.getSupplier = getSupplier;
        this.listSuppliers = listSuppliers;
        this.activateSupplier = activateSupplier;
        this.deactivateSupplier = deactivateSupplier;
        this.rateSupplier = rateSupplier;
        this.addCertificate = addCertificate;
        this.removeCertificate = removeCertificate;
    }

    @PostMapping
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> createSupplier(
            @Valid @RequestBody CreateSupplierRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Creating supplier: {} by actor: {}", request.name(), actorId.value());

        var cmd = new CreateSupplierCommand(
                request.name(), request.phone(), request.email(), request.contactPerson(),
                request.street(), request.houseNumber(), request.postalCode(),
                request.city(), request.country(),
                request.paymentDueDays(), request.paymentDescription()
        );
        var result = createSupplier.execute(cmd, actorId);

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

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

    @GetMapping
    public ResponseEntity<List<SupplierResponse>> listSuppliers(
            @RequestParam(value = "status", required = false) SupplierStatus status,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Listing suppliers by actor: {}", actorId.value());

        Result<SupplierError, List<Supplier>> result;
        if (status != null) {
            result = listSuppliers.executeByStatus(status);
        } else {
            result = listSuppliers.execute();
        }

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

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

    @GetMapping("/{id}")
    public ResponseEntity<SupplierResponse> getSupplier(
            @PathVariable("id") String supplierId,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Getting supplier: {} by actor: {}", supplierId, actorId.value());

        var result = getSupplier.execute(SupplierId.of(supplierId));

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

        return ResponseEntity.ok(SupplierResponse.from(result.unsafeGetValue()));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> updateSupplier(
            @PathVariable("id") String supplierId,
            @Valid @RequestBody UpdateSupplierRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Updating supplier: {} by actor: {}", supplierId, actorId.value());

        var cmd = new UpdateSupplierCommand(
                supplierId,
                request.name(), request.phone(), request.email(), request.contactPerson(),
                request.street(), request.houseNumber(), request.postalCode(),
                request.city(), request.country(),
                request.paymentDueDays(), request.paymentDescription()
        );
        var result = updateSupplier.execute(cmd, actorId);

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

        logger.info("Supplier updated: {}", supplierId);
        return ResponseEntity.ok(SupplierResponse.from(result.unsafeGetValue()));
    }

    @PostMapping("/{id}/activate")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> activate(
            @PathVariable("id") String supplierId,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Activating supplier: {} by actor: {}", supplierId, actorId.value());

        var result = activateSupplier.execute(SupplierId.of(supplierId), actorId);

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

        logger.info("Supplier activated: {}", supplierId);
        return ResponseEntity.ok(SupplierResponse.from(result.unsafeGetValue()));
    }

    @PostMapping("/{id}/deactivate")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> deactivate(
            @PathVariable("id") String supplierId,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Deactivating supplier: {} by actor: {}", supplierId, actorId.value());

        var result = deactivateSupplier.execute(SupplierId.of(supplierId), actorId);

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

        logger.info("Supplier deactivated: {}", supplierId);
        return ResponseEntity.ok(SupplierResponse.from(result.unsafeGetValue()));
    }

    @PostMapping("/{id}/rating")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> rateSupplier(
            @PathVariable("id") String supplierId,
            @Valid @RequestBody RateSupplierRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Rating supplier: {} by actor: {}", supplierId, actorId.value());

        var cmd = new RateSupplierCommand(
                supplierId, request.qualityScore(), request.deliveryScore(), request.priceScore()
        );
        var result = rateSupplier.execute(cmd, actorId);

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

        logger.info("Supplier rated: {}", supplierId);
        return ResponseEntity.ok(SupplierResponse.from(result.unsafeGetValue()));
    }

    @PostMapping("/{id}/certificates")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<SupplierResponse> addCertificate(
            @PathVariable("id") String supplierId,
            @Valid @RequestBody AddCertificateRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Adding certificate to supplier: {} by actor: {}", supplierId, actorId.value());

        var cmd = new AddCertificateCommand(
                supplierId, request.certificateType(), request.issuer(),
                request.validFrom(), request.validUntil()
        );
        var result = addCertificate.execute(cmd, actorId);

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

        logger.info("Certificate added to supplier: {}", supplierId);
        return ResponseEntity.status(HttpStatus.CREATED).body(SupplierResponse.from(result.unsafeGetValue()));
    }

    @DeleteMapping("/{id}/certificates")
    @PreAuthorize("hasAuthority('MASTERDATA_WRITE')")
    public ResponseEntity<Void> removeCertificate(
            @PathVariable("id") String supplierId,
            @Valid @RequestBody RemoveCertificateRequest request,
            Authentication authentication
    ) {
        var actorId = extractActorId(authentication);
        logger.info("Removing certificate from supplier: {} by actor: {}", supplierId, actorId.value());

        var cmd = new RemoveCertificateCommand(
                supplierId, request.certificateType(), request.issuer(), request.validFrom()
        );
        var result = removeCertificate.execute(cmd, actorId);

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

        logger.info("Certificate removed from supplier: {}", supplierId);
        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 SupplierDomainErrorException extends RuntimeException {
        private final SupplierError error;

        public SupplierDomainErrorException(SupplierError error) {
            super(error.message());
            this.error = error;
        }

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