package de.cannamanage.api.controller;

import de.cannamanage.domain.entity.CustomMailDomain;
import de.cannamanage.domain.entity.TenantContext;
import de.cannamanage.service.CustomMailDomainService;
import de.cannamanage.service.PlanTierService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * REST controller for Enterprise custom email domain management.
 * All endpoints require ADMIN role + Enterprise tier.
 */
@RestController
@RequestMapping("/api/v1/settings/mail")
public class MailSettingsController {

    private final CustomMailDomainService customMailDomainService;
    private final PlanTierService planTierService;

    public MailSettingsController(CustomMailDomainService customMailDomainService,
                                  PlanTierService planTierService) {
        this.customMailDomainService = customMailDomainService;
        this.planTierService = planTierService;
    }

    /**
     * Set a custom FROM address for the club's outbound emails.
     * Enterprise tier only.
     */
    @PostMapping("/custom-domain")
    public ResponseEntity<MailDomainStatusResponse> setCustomDomain(
            @Valid @RequestBody CustomMailDomainRequest request) {
        UUID tenantId = TenantContext.getCurrentTenantId();
        CustomMailDomain domain = customMailDomainService.setCustomDomain(tenantId, request.fromAddress());
        return ResponseEntity.ok(toResponse(domain));
    }

    /**
     * Get current custom domain status.
     */
    @GetMapping("/custom-domain")
    public ResponseEntity<MailDomainStatusResponse> getCustomDomain() {
        UUID tenantId = TenantContext.getCurrentTenantId();
        planTierService.requireEnterpriseTier(tenantId);

        return customMailDomainService.getCustomDomain(tenantId)
                .map(domain -> ResponseEntity.ok(toResponse(domain)))
                .orElse(ResponseEntity.noContent().build());
    }

    /**
     * Trigger DNS verification for the custom domain.
     */
    @PostMapping("/custom-domain/verify")
    public ResponseEntity<MailDomainStatusResponse> verifyCustomDomain() {
        UUID tenantId = TenantContext.getCurrentTenantId();
        CustomMailDomain domain = customMailDomainService.verifyDomain(tenantId);
        return ResponseEntity.ok(toResponse(domain));
    }

    /**
     * Remove custom domain configuration (revert to platform default).
     */
    @DeleteMapping("/custom-domain")
    public ResponseEntity<Void> removeCustomDomain() {
        UUID tenantId = TenantContext.getCurrentTenantId();
        planTierService.requireEnterpriseTier(tenantId);
        customMailDomainService.removeCustomDomain(tenantId);
        return ResponseEntity.noContent().build();
    }

    private MailDomainStatusResponse toResponse(CustomMailDomain domain) {
        return new MailDomainStatusResponse(
                domain.getFromAddress(),
                domain.getDomain(),
                domain.isVerified(),
                domain.getVerificationToken(),
                domain.getVerifiedAt() != null ? domain.getVerifiedAt().toString() : null,
                "cannamanage-verify=" + domain.getVerificationToken()
        );
    }

    // --- DTOs ---

    public record CustomMailDomainRequest(
            @NotBlank @Email String fromAddress
    ) {}

    public record MailDomainStatusResponse(
            String fromAddress,
            String domain,
            boolean verified,
            String verificationToken,
            String verifiedAt,
            String requiredDnsTxtRecord
    ) {}
}
