<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AuditLogController extends Controller
{
    public function index(Request $request): Response
    {
        $action = trim((string) $request->string('action'));
        $targetType = trim((string) $request->string('target_type'));
        $actorUserId = $request->integer('actor_user_id') ?: null;
        $targetId = $request->integer('target_id') ?: null;
        $fromDate = trim((string) $request->string('from_date'));
        $toDate = trim((string) $request->string('to_date'));
        $q = trim((string) $request->string('q'));

        $query = AuditLog::query()
            ->with('actor:id,name,email')
            ->orderByDesc('id');

        if ($action !== '') {
            $query->where('action', $action);
        }

        if ($targetType !== '') {
            $query->where('target_type', $targetType);
        }

        if ($actorUserId !== null) {
            $query->where('actor_user_id', $actorUserId);
        }

        if ($targetId !== null) {
            $query->where('target_id', $targetId);
        }

        // Loose YYYY-MM-DD parsing — invalid input gets ignored rather than
        // 422'd. Filters are exploratory, not authoritative.
        if ($fromDate !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $fromDate)) {
            $query->where('created_at', '>=', $fromDate.' 00:00:00');
        }

        if ($toDate !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $toDate)) {
            $query->where('created_at', '<=', $toDate.' 23:59:59');
        }

        if ($q !== '') {
            $query->where('summary', 'like', '%'.$q.'%');
        }

        $paginator = $query->paginate(50)->withQueryString();

        $logs = $paginator->through(fn (AuditLog $l) => [
            'id' => $l->id,
            'action' => $l->action,
            'target_type' => $l->target_type,
            'target_id' => $l->target_id,
            'summary' => $l->summary,
            'context' => $l->context,
            'ip' => $l->ip,
            'user_agent' => $l->user_agent,
            'created_at' => $l->created_at?->toIso8601String(),
            'actor' => $l->actor ? [
                'id' => $l->actor->id,
                'name' => $l->actor->name,
                'email' => $l->actor->email,
            ] : null,
        ]);

        return Inertia::render('Admin/AuditLog/Index', [
            'logs' => $logs,
            'filters' => [
                'action' => $action,
                'target_type' => $targetType,
                'actor_user_id' => $actorUserId,
                'target_id' => $targetId,
                'from_date' => $fromDate,
                'to_date' => $toDate,
                'q' => $q,
            ],
            'actions' => AuditLog::query()->distinct()->orderBy('action')->pluck('action'),
            'target_types' => AuditLog::query()->whereNotNull('target_type')->distinct()->orderBy('target_type')->pluck('target_type'),
        ]);
    }
}
