package com.saas.subscription.controller;

import com.saas.subscription.entity.SubscriptionPlan;
import com.saas.subscription.entity.TenantSubscription;
import com.saas.subscription.service.SubscriptionService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/subscription")
@RequiredArgsConstructor
public class SubscriptionAdminController {

    private final SubscriptionService subscriptionService;

    @PostMapping("/plans")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public ResponseEntity<SubscriptionPlan> createPlan(@RequestBody SubscriptionPlan plan) {
        return ResponseEntity.ok(subscriptionService.createPlan(plan));
    }

    @GetMapping("/plans")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public ResponseEntity<List<SubscriptionPlan>> getAllPlans() {
        return ResponseEntity.ok(subscriptionService.getAllPlans());
    }

    @PostMapping("/assign")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public ResponseEntity<TenantSubscription> assignPlan(
            @RequestParam String tenantId,
            @RequestParam Long planId) {
        return ResponseEntity.ok(subscriptionService.assignPlanToTenant(tenantId, planId));
    }

    @GetMapping("/tenant/{tenantId}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public ResponseEntity<TenantSubscription> getTenantSubscription(@PathVariable String tenantId) {
        return subscriptionService.getTenantSubscription(tenantId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}
