<?php

namespace App\Http\Controllers;

use App\Http\Resources\AuditableResource;
use App\Http\Resources\AuditListResource;
use App\Http\Resources\AuditViewResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\Audit;
use Mtc\MercuryDataModels\Setting;

class AuditController extends Controller
{
    public function index(Request $request): AuditListResource
    {
        $entries = Audit::query()
            ->when(
                $request->filled('user') && $request->input('user') !== 'null',
                fn ($query) => $query->where('user_id', $request->input('user'))
            )
            ->when(
                $request->filled('type') && $request->input('type') !== 'All',
                fn ($query) => $query->where('auditable_type', $request->input('type'))
            )
            ->when(
                $request->filled('entry') && $request->input('entry') !== 'null',
                fn ($query) => $query->where('auditable_id', $request->input('entry'))
            )
            ->with([
                'user',
                'auditable',
            ])
            ->setSortBy($request->input('sort_by'))
            ->paginate();
        return new AuditListResource($entries);
    }

    public function show(Audit $audit): AuditViewResource
    {
        return new AuditViewResource($audit);
    }

    public function forAuditable(Request $request): AuditableResource|JsonResponse
    {
        $auditableType = $request->input('type');
        $auditableId = $request->input('id');

        if (!$auditableType || !$auditableId) {
            return response()->json([
                'audits' => [],
            ]);
        }

        return new AuditableResource($auditableType, $auditableId);
    }

    public function forSetting(Request $request): JsonResponse
    {
        if (!Auth::user()->hasRole('mtc')) {
            return response()->json([
                'audits' => [],
                'last_audit' => null,
            ]);
        }

        $configKey = $request->input('config_key');

        $setting = Setting::query()
            ->where('config_key', $configKey)
            ->first();

        if (!$setting) {
            return response()->json([
                'audits' => [],
                'last_audit' => null,
            ]);
        }

        $audits = Audit::query()
            ->where('auditable_type', 'setting')
            ->where('auditable_id', $setting->id)
            ->with('user')
            ->orderByDesc('created_at')
            ->limit(50)
            ->get()
            ->map(fn (Audit $audit) => [
                'id' => $audit->id,
                'event' => $audit->event,
                'created_at' => $audit->created_at->format('d/m/Y H:i'),
                'user_name' => $audit->user?->name ?? 'System',
                'old_values' => $audit->old_values,
                'new_values' => $audit->new_values,
            ]);

        return response()->json([
            'audits' => $audits,
            'last_audit' => $audits->first(),
        ]);
    }
}
