package net.siegeln.cameleer.saas.onboarding;

import jakarta.validation.Valid;
import java.util.Map;
import net.siegeln.cameleer.saas.tenant.TenantEntity;
import net.siegeln.cameleer.saas.tenant.dto.TenantResponse;
import net.siegeln.cameleer.saas.tenant.TenantRepository;
import net.siegeln.cameleer.saas.tenant.TenantStatus;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/onboarding")
public class OnboardingController {

    private final OnboardingService onboardingService;
    private final TenantRepository tenantRepository;

    public OnboardingController(OnboardingService onboardingService, TenantRepository tenantRepository) {
        this.onboardingService = onboardingService;
        this.tenantRepository = tenantRepository;
    }

    public record CreateTrialTenantRequest(
            @jakarta.validation.constraints.NotBlank
            @jakarta.validation.constraints.Size(max = 255)
            String name,

            @jakarta.validation.constraints.NotBlank
            @jakarta.validation.constraints.Size(max = 100)
            @jakarta.validation.constraints.Pattern(
                    regexp = "^[a-z0-9][a-z0-9-]*[a-z0-9]$",
                    message = "Slug must be lowercase alphanumeric with hyphens")
            String slug
    ) {}

    @GetMapping("/slug-available")
    public ResponseEntity<Map<String, Boolean>> slugAvailable(@RequestParam String slug) {
        boolean taken = tenantRepository.existsBySlugAndStatusNot(slug, TenantStatus.DELETED);
        return ResponseEntity.ok(Map.of("available", !taken));
    }

    @PostMapping("/tenant")
    public ResponseEntity<TenantResponse> createTrialTenant(
            @Valid @RequestBody CreateTrialTenantRequest request,
            @AuthenticationPrincipal Jwt jwt) {

        String userId = jwt.getSubject();
        try {
            TenantEntity tenant = onboardingService.createTrialTenant(request.name(), request.slug(), userId);
            return ResponseEntity.status(HttpStatus.CREATED).body(TenantResponse.from(tenant));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
    }
}
