package com.saas.subscription.controller;

import com.saas.subscription.dto.request.CreateSubscriptionPlanRequest;
import com.saas.subscription.dto.response.SubscriptionPlanResponse;
import com.saas.subscription.service.SubscriptionPlanService;
import com.saas.shared.dto.common.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * REST Controller for subscription plan management.
 * 
 * Path: /api/admin/subscription-plans
 * Role: SYSTEM_ADMIN only
 * 
 * Endpoints:
 * - POST   /           Create new plan
 * - GET    /           List all active plans
 * - GET    /{id}       Get plan details
 * - PUT    /{id}       Update plan
 * - DELETE /{id}       Deactivate plan
 */
@RestController
@RequestMapping("/api/admin/subscription-plans")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Subscription Plans", description = "Manage subscription pricing plans")
@SecurityRequirement(name = "Bearer Authentication")
public class AdminSubscriptionPlanController {

    private final SubscriptionPlanService planService;

    @PostMapping
    @Operation(summary = "Create subscription plan", description = "Create new subscription plan with features and pricing")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "201",
            description = "Plan created successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "Validation error"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden - requires SYSTEM_ADMIN role"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "409", description = "Plan name already exists")
    })
    public ResponseEntity<ApiResponse<SubscriptionPlanResponse>> createPlan(
            @Valid @RequestBody CreateSubscriptionPlanRequest request) {
        log.info("Creating subscription plan: {}", request.getName());

        SubscriptionPlanResponse response = planService.createPlan(request);

        return ResponseEntity.status(HttpStatus.CREATED)
            .body(ApiResponse.success(response, "Subscription plan created successfully"));
    }

    @GetMapping
    @Operation(summary = "List active subscription plans", description = "Retrieve all active subscription plans sorted by price")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Plans retrieved successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden")
    })
    public ResponseEntity<ApiResponse<List<SubscriptionPlanResponse>>> getAllPlans() {
        log.info("Fetching all active subscription plans");

        List<SubscriptionPlanResponse> plans = planService.getAllActivePlans();

        return ResponseEntity.ok()
            .body(ApiResponse.success(plans, "Subscription plans retrieved successfully"));
    }

    @GetMapping("/{planId}")
    @Operation(summary = "Get plan details", description = "Retrieve specific subscription plan with all features")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Plan found",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Plan not found")
    })
    public ResponseEntity<ApiResponse<SubscriptionPlanResponse>> getPlan(
            @Parameter(description = "Subscription plan ID", example = "1")
            @PathVariable Long planId) {
        log.info("Fetching subscription plan: {}", planId);

        SubscriptionPlanResponse plan = planService.getPlan(planId);

        return ResponseEntity.ok()
            .body(ApiResponse.success(plan, "Subscription plan retrieved successfully"));
    }

    @PutMapping("/{planId}")
    @Operation(summary = "Update subscription plan", description = "Update plan features and pricing")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "Plan updated successfully",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "Validation error"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Plan not found"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "409", description = "Plan name already taken")
    })
    public ResponseEntity<ApiResponse<SubscriptionPlanResponse>> updatePlan(
            @Parameter(description = "Subscription plan ID", example = "1")
            @PathVariable Long planId,
            @Valid @RequestBody CreateSubscriptionPlanRequest request) {
        log.info("Updating subscription plan: {}", planId);

        SubscriptionPlanResponse response = planService.updatePlan(planId, request);

        return ResponseEntity.ok()
            .body(ApiResponse.success(response, "Subscription plan updated successfully"));
    }

    @DeleteMapping("/{planId}")
    @Operation(summary = "Deactivate subscription plan", description = "Soft-delete plan (existing subscriptions continue, new ones cannot use)")
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "204", description = "Plan deleted successfully"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "Unauthorized"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "Forbidden"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Plan not found")
    })
    public ResponseEntity<Void> deletePlan(
            @Parameter(description = "Subscription plan ID", example = "1")
            @PathVariable Long planId) {
        log.info("Deactivating subscription plan: {}", planId);

        planService.deletePlan(planId);

        return ResponseEntity.noContent().build();
    }
}
