package com.saas.admin.controller;

import com.saas.admin.dto.request.CreateTenantRequest;
import com.saas.admin.dto.response.TenantResponse;
import com.saas.admin.service.TenantService;
import com.saas.shared.dto.common.ApiResponse;
import com.saas.shared.dto.common.PageResponse;
import io.swagger.v3.oas.annotations.Operation;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/admin/tenants")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Admin - Tenant Management", description = "Operations for managing tenants")
@PreAuthorize("hasRole('SYSTEM_ADMIN')")
public class AdminTenantController {

    private final TenantService tenantService;

    @PostMapping
    @Operation(summary = "Create a new tenant", description = "Creates a new tenant and initializes their database schema")
    public ResponseEntity<ApiResponse<TenantResponse>> createTenant(@Valid @RequestBody CreateTenantRequest request) {
        log.info("Request to create tenant: {}", request.getTenantName());
        TenantResponse tenant = tenantService.createTenant(request);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(ApiResponse.success(tenant, "Tenant created successfully"));
    }

    @GetMapping
    @Operation(summary = "Get all tenants (Paginated)", description = "Retrieve a paginated list of all tenants")
    public ResponseEntity<ApiResponse<PageResponse<TenantResponse>>> getTenants(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        log.info("Request to list tenants - page: {}, size: {}", page, size);
        PageResponse<TenantResponse> tenants = tenantService.getTenants(page, size);
        return ResponseEntity.ok(ApiResponse.success(tenants, "Tenants retrieved successfully"));
    }

    @GetMapping("/{id}")
    @Operation(summary = "Get tenant by ID", description = "Retrieve details of a specific tenant")
    public ResponseEntity<ApiResponse<TenantResponse>> getTenantById(@PathVariable String id) {
        log.info("Request to get tenant: {}", id);
        TenantResponse tenant = tenantService.getTenantById(id);
        return ResponseEntity.ok(ApiResponse.success(tenant, "Tenant retrieved successfully"));
    }

    @PutMapping("/{id}")
    @Operation(summary = "Update tenant status", description = "Update the status of a tenant (e.g., ACTIVE, SUSPENDED)")
    public ResponseEntity<ApiResponse<TenantResponse>> updateTenant(
            @PathVariable String id,
            @RequestParam String status) {
        log.info("Request to update tenant status: {} -> {}", id, status);
        TenantResponse tenant = tenantService.updateTenant(id, status);
        return ResponseEntity.ok(ApiResponse.success(tenant, "Tenant updated successfully"));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "Delete tenant", description = "Permanently delete a tenant and their data")
    public ResponseEntity<ApiResponse<Void>> deleteTenant(@PathVariable String id) {
        log.info("Request to delete tenant: {}", id);
        tenantService.deleteTenant(id);
        return ResponseEntity.ok(ApiResponse.success(null, "Tenant deleted successfully"));
    }

    @PostMapping("/{id}/assign-ai")
    @Operation(summary = "Assign AI Assistant", description = "Assigns a Vapi or Retell assistant to the tenant")
    public ResponseEntity<ApiResponse<Void>> assignAiAssistant(
            @PathVariable String id,
            @RequestParam String provider,
            @RequestParam String assistantId,
            @RequestParam(required = false) String phoneNumberId) {
        tenantService.assignAiAssistant(id, provider, assistantId, phoneNumberId);
        return ResponseEntity.ok(ApiResponse.success(null, "AI Assistant assigned successfully"));
    }
}
