<?php

namespace App\Models;

use CodeIgniter\Model;

class ReportSummaryModel extends Model
{
    protected $table         = 'report_summaries';
    protected $useTimestamps = false;
    protected $allowedFields = ['report_key', 'scope', 'agency_id', 'period_date', 'metrics', 'generated_at'];
    protected $casts         = ['metrics' => 'json'];

    public function upsert(string $reportKey, string $scope, ?int $agencyId, string $periodDate, array $metrics): void
    {
        $existing = $this->where('report_key', $reportKey)
            ->where('scope', $scope)
            ->where('agency_id', $agencyId)
            ->where('period_date', $periodDate)
            ->first();

        $data = ['metrics' => json_encode($metrics), 'generated_at' => date('Y-m-d H:i:s')];

        if ($existing) {
            $this->update($existing['id'], $data);
        } else {
            $this->insert(array_merge($data, [
                'report_key' => $reportKey, 'scope' => $scope, 'agency_id' => $agencyId, 'period_date' => $periodDate,
            ]));
        }
    }

    public function rangeFor(string $reportKey, string $scope, ?int $agencyId, string $from, string $to): array
    {
        return $this->where('report_key', $reportKey)
            ->where('scope', $scope)
            ->where('agency_id', $agencyId)
            ->where('period_date >=', $from)
            ->where('period_date <=', $to)
            ->orderBy('period_date', 'ASC')
            ->findAll();
    }
}
