<?php

namespace App\Modules\Operations\Repositories;

use App\Modules\Operations\Models\OperationalControlEvent;
use Illuminate\Database\Eloquent\Collection;

class OperationalControlEventRepository
{
    /**
     * @param  array<string, mixed>  $row
     */
    public function insert(array $row): void
    {
        OperationalControlEvent::withoutGlobalScopes()->create($row);
    }

    /**
     * @return Collection<int, OperationalControlEvent>
     */
    public function recentUnacknowledged(int $tenantId, int $days, int $limit): Collection
    {
        $since = now()->subDays($days);

        return OperationalControlEvent::query()
            ->where('tenant_id', $tenantId)
            ->whereNull('acknowledged_at')
            ->where('created_at', '>=', $since)
            ->orderByDesc('severity')
            ->orderByDesc('created_at')
            ->limit($limit)
            ->get();
    }

    public function acknowledge(int $tenantId, int $eventId, int $userId): bool
    {
        $q = OperationalControlEvent::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($eventId)
            ->whereNull('acknowledged_at');

        return $q->update([
            'acknowledged_at' => now(),
            'acknowledged_by' => $userId,
        ]) > 0;
    }
}
