<?php

namespace App\Services;

use App\Models\Commons\CategoryLog;
use Illuminate\Support\Carbon;

class CategoryLogService extends Service
{
    public function index(int $categoryId, array $params)
    {
        $tenantId = $this->tenantId();

        $size = (int) ($params['size'] ?? 20);
        $action = $params['action'] ?? null; // insert|update|delete
        $from = $params['from'] ?? null; // Y-m-d
        $to = $params['to'] ?? null;

        $q = CategoryLog::query()
            ->where('tenant_id', $tenantId)
            ->where('category_id', $categoryId)
            ->orderByDesc('changed_at');

        if ($action) {
            $q->where('action', $action);
        }
        if ($from) {
            $q->whereDate('changed_at', '>=', Carbon::parse($from)->toDateString());
        }
        if ($to) {
            $q->whereDate('changed_at', '<=', Carbon::parse($to)->toDateString());
        }

        return $q->paginate($size);
    }

    public function show(int $logId)
    {
        $tenantId = $this->tenantId();

        $log = CategoryLog::query()
            ->where('tenant_id', $tenantId)
            ->find($logId);

        if (! $log) {
            throw new BadRequestHttpException(__('error.not_found'));
        }

        return $log;
    }
}
