<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectAuditLog;
use App\Services\RolePermissionService;
use Illuminate\Http\Request;

class AuditLogController extends Controller
{
    public function __construct(private readonly RolePermissionService $rolePermissionService)
    {
    }

    /**
     * Get audit logs for a specific project.
     */
    public function projectLogs(int $projectId, Request $request)
    {
        $user = auth('api')->user();
        if (!$this->hasAnyPermission($user->role, ['view_audit_logs', 'manage_role_permissions', 'manage_users'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $project = Project::find($projectId);
        if (!$project) {
            return response()->json(['message' => 'Project not found'], 404);
        }

        $query = ProjectAuditLog::where('project_id', $projectId)
            ->with('user:id,name,email,role')
            ->orderBy('performed_at', 'desc');

        if ($request->filled('action')) {
            $query->where('action', $request->action);
        }

        if ($request->filled('entity_type')) {
            $query->where('entity_type', $request->entity_type);
        }

        if ($request->filled('limit')) {
            $query->limit(intval($request->limit));
        } else {
            $query->limit(100);
        }

        return response()->json([
            'data' => $query->get(),
        ]);
    }

    /**
     * Get all audit logs (admin only).
     */
    public function allLogs(Request $request)
    {
        $user = auth('api')->user();
        if (!$this->hasAnyPermission($user->role, ['view_audit_logs', 'manage_role_permissions'])) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $query = ProjectAuditLog::with(['project:id,name', 'user:id,name,email,role'])
            ->orderBy('performed_at', 'desc');

        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }

        if ($request->filled('action')) {
            $query->where('action', $request->action);
        }

        if ($request->filled('performed_by')) {
            $query->where('performed_by', $request->performed_by);
        }

        $limit = $request->filled('limit') ? intval($request->limit) : 200;
        $query->limit($limit);

        return response()->json([
            'data' => $query->get(),
        ]);
    }

    private function hasAnyPermission(string $roleId, array $requiredPermissions): bool
    {
        return $this->rolePermissionService->hasAnyPermission($roleId, $requiredPermissions);
    }

    private function getRolePermissions(string $roleId): array
    {
        return $this->rolePermissionService->getPermissions($roleId);
    }
}
