<?php

namespace App\Http\Controllers;

use App\Enums\LogType;
use App\Models\Logs;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class LogsController
{
    public function index(Request $request): JsonResponse
    {
        $logs = Logs::query()
            ->when($request->filled('type'), function (Builder $query) use ($request) {
                $type = $request->string('type')->lower()->toString();

                return collect(LogType::cases())
                    ->firstWhere('value', $type)
                    ? $query->where('log_type', $type)
                    : $query;
            })
            ->when($request->boolean('priority'), function (Builder $query) {
                $priorityTypes = collect(LogType::cases())
                    ->filter(fn (LogType $type) => $type->isPriority())
                    ->map->value
                    ->all();

                return $query->whereIn('log_type', $priorityTypes);
            })
            ->when($request->has('visible'), function (Builder $query) use ($request) {
                return $query->where('visible', $request->boolean('visible'));
            })
            ->orderByDesc('created_at')
            ->paginate($request->integer('per_page', 50));

        return response()->json($logs);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'log_type' => ['required', Rule::enum(LogType::class)],
            'message' => ['required', 'string'],
            'user_id' => ['nullable', 'exists:users,id'],
            'customer_id' => ['nullable', 'exists:users,id'],
            'visible' => ['sometimes', 'boolean'],
            'ip_address' => ['nullable', 'ip'],
        ]);

        $log = Logs::create([
            'log_type' => $validated['log_type'],
            'user_id' => $validated['user_id'] ?? $request->user()?->getAuthIdentifier(),
            'customer_id' => $validated['customer_id'] ?? null,
            'message' => $validated['message'],
            'ip_address' => $validated['ip_address'] ?? $request->ip(),
            'visible' => $validated['visible'] ?? true,
        ]);

        return response()->json($log, 201);
    }

    public function destroy(Logs $log): JsonResponse
    {
        $log->delete();

        return response()->json([
            'status' => 'deleted',
            'log_id' => $log->getKey(),
        ]);
    }
}
