<?php

namespace App\Http\Controllers;

use App\Models\RoleMapping;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RoleMappingController extends Controller
{
    public function index()
    {
        $mappings = RoleMapping::with(['user', 'role'])->get();
        return response()->json([
            'status' => 'success',
            'message' => 'Role mappings retrieved successfully',
            'data' => $mappings
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'U_Id' => 'required|exists:users_master,U_Id',
            'Role_Id' => 'required|exists:role_master,Role_Id',
            'Default_Rid' => 'required|integer|in:0,1',
        ], [
            'U_Id.required' => 'User ID is required.',
            'U_Id.exists' => 'The selected user does not exist.',
            'Role_Id.required' => 'Role ID is required.',
            'Role_Id.exists' => 'The selected role does not exist.',
            'Default_Rid.required' => 'Default role indicator is required.',
            'Default_Rid.integer' => 'Default role indicator must be an integer (0 or 1).',
            'Default_Rid.in' => 'Default role indicator must be 0 (non-default) or 1 (default).',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $validatedData = $validator->validated();

        // Ensure only one SuperAdmin (Role_Id = 1)
        if ($validatedData['Role_Id'] == 1) {
            $existingSuperAdmin = RoleMapping::where('Role_Id', 1)
                ->where('U_Id', '!=', $validatedData['U_Id'])
                ->exists();
            if ($existingSuperAdmin) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'A SuperAdmin already exists. Only one SuperAdmin is allowed.'
                ], 403);
            }
        }

        // Ensure only one default role per user
        if ($validatedData['Default_Rid'] == 1) {
            $existingDefault = RoleMapping::where('U_Id', $validatedData['U_Id'])
                ->where('Default_Rid', 1)
                ->exists();
            if ($existingDefault) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This user already has a default role. Only one default role is allowed per user.'
                ], 403);
            }
        }

        try {
            $mapping = RoleMapping::create($validatedData);
            $mapping->load(['user', 'role']);
            return response()->json([
                'status' => 'success',
                'message' => 'Role mapping created successfully',
                'data' => $mapping
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while creating the role mapping.'
            ], 500);
        }
    }

    public function show($id)
    {
        $mapping = RoleMapping::with(['user', 'role'])->find($id);
        if (!$mapping) {
            return response()->json([
                'status' => 'error',
                'message' => 'Role mapping not found'
            ], 404);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Role mapping retrieved successfully',
            'data' => $mapping
        ], 200);
    }

    public function update(Request $request, $id)
    {
        $mapping = RoleMapping::find($id);
        if (!$mapping) {
            return response()->json([
                'status' => 'error',
                'message' => 'Role mapping not found'
            ], 404);
        }

        $validator = Validator::make($request->all(), [
            'U_Id' => 'sometimes|exists:users_master,U_Id',
            'Role_Id' => 'sometimes|exists:role_master,Role_Id',
            'Default_Rid' => 'sometimes|integer|in:0,1',
        ], [
            'U_Id.exists' => 'The selected user does not exist.',
            'Role_Id.exists' => 'The selected role does not exist.',
            'Default_Rid.integer' => 'Default role indicator must be an integer (0 or 1).',
            'Default_Rid.in' => 'Default role indicator must be 0 (non-default) or 1 (default).',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $validatedData = $request->only(['U_Id', 'Role_Id', 'Default_Rid']);

        // Ensure only one SuperAdmin (Role_Id = 1)
        if (isset($validatedData['Role_Id']) && $validatedData['Role_Id'] == 1) {
            $existingSuperAdmin = RoleMapping::where('Role_Id', 1)
                ->where('URoleMap', '!=', $id)
                ->exists();
            if ($existingSuperAdmin) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'A SuperAdmin already exists. Only one SuperAdmin is allowed.'
                ], 403);
            }
        }

        // Ensure only one default role per user
        if (isset($validatedData['Default_Rid']) && $validatedData['Default_Rid'] == 1) {
            $userId = $validatedData['U_Id'] ?? $mapping->U_Id;
            $existingDefault = RoleMapping::where('U_Id', $userId)
                ->where('Default_Rid', 1)
                ->where('URoleMap', '!=', $id)
                ->exists();
            if ($existingDefault) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This user already has a default role. Only one default role is allowed per user.'
                ], 403);
            }
        }

        try {
            $mapping->update($validatedData);
            $mapping->load(['user', 'role']);
            return response()->json([
                'status' => 'success',
                'message' => 'Role mapping updated successfully',
                'data' => $mapping
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while updating the role mapping.'
            ], 500);
        }
    }

    public function destroy($id)
    {
        $mapping = RoleMapping::find($id);
        if (!$mapping) {
            return response()->json([
                'status' => 'error',
                'message' => 'Role mapping not found'
            ], 404);
        }

        try {
            $mapping->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Role mapping deleted successfully'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred while deleting the role mapping.'
            ], 500);
        }
    }
}
