package com.cameleer.server.app.controller;

import com.cameleer.server.core.admin.AuditCategory;
import com.cameleer.server.core.admin.AuditResult;
import com.cameleer.server.core.admin.AuditService;
import com.cameleer.server.core.rbac.RoleDetail;
import com.cameleer.server.core.rbac.RoleRepository;
import com.cameleer.server.core.rbac.SystemRole;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Admin endpoints for role management.
 * Protected by {@code ROLE_ADMIN}.
 */
@RestController
@RequestMapping("/api/v1/admin/roles")
@Tag(name = "Role Admin", description = "Role management (ADMIN only)")
@PreAuthorize("hasRole('ADMIN')")
public class RoleAdminController {

    private final RoleRepository roleRepository;
    private final AuditService auditService;

    public RoleAdminController(RoleRepository roleRepository, AuditService auditService) {
        this.roleRepository = roleRepository;
        this.auditService = auditService;
    }

    @GetMapping
    @Operation(summary = "List all roles (system and custom)")
    @ApiResponse(responseCode = "200", description = "Role list returned")
    public ResponseEntity<List<RoleDetail>> listRoles() {
        return ResponseEntity.ok(roleRepository.findAll());
    }

    @GetMapping("/{id}")
    @Operation(summary = "Get role by ID with effective principals")
    @ApiResponse(responseCode = "200", description = "Role found")
    @ApiResponse(responseCode = "404", description = "Role not found")
    public ResponseEntity<RoleDetail> getRole(@PathVariable UUID id) {
        return roleRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @Operation(summary = "Create a custom role")
    @ApiResponse(responseCode = "200", description = "Role created")
    public ResponseEntity<Map<String, UUID>> createRole(@RequestBody CreateRoleRequest request,
                                                         HttpServletRequest httpRequest) {
        String desc = request.description() != null ? request.description() : "";
        String sc = request.scope() != null ? request.scope() : "custom";
        UUID id = roleRepository.create(request.name(), desc, sc);
        auditService.log("create_role", AuditCategory.RBAC, id.toString(),
                Map.of("name", request.name()), AuditResult.SUCCESS, httpRequest);
        return ResponseEntity.ok(Map.of("id", id));
    }

    @PutMapping("/{id}")
    @Operation(summary = "Update a custom role")
    @ApiResponse(responseCode = "200", description = "Role updated")
    @ApiResponse(responseCode = "403", description = "Cannot modify system role")
    @ApiResponse(responseCode = "404", description = "Role not found")
    public ResponseEntity<Void> updateRole(@PathVariable UUID id,
                                            @RequestBody UpdateRoleRequest request,
                                            HttpServletRequest httpRequest) {
        if (SystemRole.isSystem(id)) {
            auditService.log("update_role", AuditCategory.RBAC, id.toString(),
                    Map.of("reason", "system_role_protected"), AuditResult.FAILURE, httpRequest);
            return ResponseEntity.status(403).build();
        }
        if (roleRepository.findById(id).isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        roleRepository.update(id, request.name(), request.description(), request.scope());
        auditService.log("update_role", AuditCategory.RBAC, id.toString(),
                null, AuditResult.SUCCESS, httpRequest);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "Delete a custom role")
    @ApiResponse(responseCode = "204", description = "Role deleted")
    @ApiResponse(responseCode = "403", description = "Cannot delete system role")
    @ApiResponse(responseCode = "404", description = "Role not found")
    public ResponseEntity<Void> deleteRole(@PathVariable UUID id,
                                            HttpServletRequest httpRequest) {
        if (SystemRole.isSystem(id)) {
            auditService.log("delete_role", AuditCategory.RBAC, id.toString(),
                    Map.of("reason", "system_role_protected"), AuditResult.FAILURE, httpRequest);
            return ResponseEntity.status(403).build();
        }
        if (roleRepository.findById(id).isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        roleRepository.delete(id);
        auditService.log("delete_role", AuditCategory.RBAC, id.toString(),
                null, AuditResult.SUCCESS, httpRequest);
        return ResponseEntity.noContent().build();
    }

    public record CreateRoleRequest(String name, String description, String scope) {}
    public record UpdateRoleRequest(String name, String description, String scope) {}
}
