<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityAssignmentRule;
use App\Services\ActivityAssignmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ActivityAssignmentController extends Controller
{
    public function __construct(
        protected ActivityAssignmentService $activityAssignmentService
    ) {}

    /**
     * Check if activity is mandatory for current user.
     */
    public function checkMandatory(Request $request): JsonResponse
    {
        $user = $request->user();

        $isMandatory = $this->activityAssignmentService->isActivityMandatoryForUser($user);

        return response()->json([
            'success' => true,
            'data' => [
                'is_mandatory' => $isMandatory,
                'activity_enabled' => $user->company->activity_mandatory_enabled ?? false,
                'scope' => $user->company->activity_mandatory_scope ?? 'all',
            ],
        ]);
    }

    /**
     * List all activity assignment rules (admin only).
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $rules = $this->activityAssignmentService->getRulesForCompany($user->company_id);

        return response()->json([
            'success' => true,
            'data' => $rules->map(function ($rule) {
                return [
                    'id' => $rule->id,
                    'rule_type' => $rule->rule_type,
                    'rule_type_label' => $rule->rule_type_label,
                    'target_values' => $rule->target_values,
                    'frequency' => $rule->frequency,
                    'is_active' => $rule->is_active,
                    'description' => $rule->description,
                    'created_at' => $rule->created_at->toIso8601String(),
                ];
            }),
        ]);
    }

    /**
     * Create a new assignment rule (admin only).
     */
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'rule_type' => 'required|in:all_users,specific_users,departments,positions',
            'target_values' => 'nullable|array',
            'frequency' => 'nullable|in:daily,weekly',
            'is_active' => 'nullable|boolean',
        ]);

        // Validate target_values based on rule_type
        if ($request->rule_type !== 'all_users' && empty($request->target_values)) {
            return response()->json([
                'success' => false,
                'message' => 'Target values diperlukan untuk tipe rule ini',
            ], 422);
        }

        $rule = $this->activityAssignmentService->createRule([
            'company_id' => $user->company_id,
            'rule_type' => $request->rule_type,
            'target_values' => $request->target_values,
            'frequency' => $request->frequency ?? 'daily',
            'is_active' => $request->is_active ?? true,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Rule berhasil dibuat',
            'data' => $rule,
        ], 201);
    }

    /**
     * Update an existing rule (admin only).
     */
    public function update(Request $request, string $id): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $rule = ActivityAssignmentRule::find($id);

        if (!$rule) {
            return response()->json([
                'success' => false,
                'message' => 'Rule tidak ditemukan',
            ], 404);
        }

        // Verify same company
        if ($rule->company_id !== $user->company_id && !$user->hasRole('super_admin')) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'rule_type' => 'nullable|in:all_users,specific_users,departments,positions',
            'target_values' => 'nullable|array',
            'frequency' => 'nullable|in:daily,weekly',
            'is_active' => 'nullable|boolean',
        ]);

        $updateData = array_filter([
            'rule_type' => $request->rule_type,
            'target_values' => $request->target_values,
            'frequency' => $request->frequency,
            'is_active' => $request->is_active,
        ], fn($value) => $value !== null);

        $rule = $this->activityAssignmentService->updateRule($rule, $updateData);

        return response()->json([
            'success' => true,
            'message' => 'Rule berhasil diupdate',
            'data' => $rule,
        ]);
    }

    /**
     * Delete a rule (admin only).
     */
    public function destroy(Request $request, string $id): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $rule = ActivityAssignmentRule::find($id);

        if (!$rule) {
            return response()->json([
                'success' => false,
                'message' => 'Rule tidak ditemukan',
            ], 404);
        }

        // Verify same company
        if ($rule->company_id !== $user->company_id && !$user->hasRole('super_admin')) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $this->activityAssignmentService->deleteRule($rule);

        return response()->json([
            'success' => true,
            'message' => 'Rule berhasil dihapus',
        ]);
    }

    /**
     * Get assignment statistics (admin only).
     */
    public function statistics(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $stats = $this->activityAssignmentService->getAssignmentStatistics($user->company);

        return response()->json([
            'success' => true,
            'data' => $stats,
        ]);
    }

    /**
     * Get available departments (admin only).
     */
    public function departments(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $departments = $this->activityAssignmentService->getAvailableDepartments($user->company);

        return response()->json([
            'success' => true,
            'data' => $departments,
        ]);
    }

    /**
     * Get available positions (admin only).
     */
    public function positions(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $positions = $this->activityAssignmentService->getAvailablePositions($user->company);

        return response()->json([
            'success' => true,
            'data' => $positions,
        ]);
    }

    /**
     * Preview rule effect (admin only).
     */
    public function preview(Request $request): JsonResponse
    {
        $user = $request->user();

        if (!$user->hasRole(['admin', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        $request->validate([
            'rule_type' => 'required|in:all_users,specific_users,departments,positions',
            'target_values' => 'nullable|array',
        ]);

        $users = $this->activityAssignmentService->previewRuleEffect(
            company: $user->company,
            ruleType: $request->rule_type,
            targetValues: $request->target_values
        );

        return response()->json([
            'success' => true,
            'data' => [
                'affected_count' => $users->count(),
                'users' => $users->map(fn($u) => [
                    'id' => $u->id,
                    'name' => $u->name,
                    'employee_id' => $u->employee_id,
                    'department' => $u->department,
                    'position' => $u->position,
                ]),
            ],
        ]);
    }
}
