<?php

namespace App\Services;

use App\Models\Claim\Claim;

class AppMilestoneService
{
    public const DEFAULT_RECEIVAL_DAYS = 14;

    public function recordReceived(Claim $claim): void
    {
        $this->refreshOutstandingEstimates((int) $claim->solicitor_id);
    }

    public function refreshOutstandingEstimates(int $solicitorId): void
    {
        $averageDays = $this->averageReceivalDays($solicitorId);

        Claim::withoutGlobalScopes()
            ->where('solicitor_id', $solicitorId)
            ->whereNull('deleted_at')
            ->whereNotNull('app_sent_date')
            ->whereNull('app_receival_date')
            ->get(['id', 'app_sent_date', 'app_est_receival_date'])
            ->each(function (Claim $claim) use ($averageDays) {
                $estimate = $claim->app_sent_date->copy()->addDays($averageDays)->toDateString();
                if ($claim->app_est_receival_date?->toDateString() !== $estimate) {
                    $claim->forceFill(['app_est_receival_date' => $estimate])->saveQuietly();
                }
            });
    }

    public function averageReceivalDays(int $solicitorId): int
    {
        $result = Claim::where('solicitor_id', $solicitorId)
            ->whereNotNull('app_sent_date')
            ->whereNotNull('app_receival_date')
            ->whereColumn('app_receival_date', '>=', 'app_sent_date')
            ->selectRaw('AVG(DATEDIFF(app_receival_date, app_sent_date)) AS average_days')
            ->first();
        $average = $result?->getAttribute('average_days');

        return $average === null
            ? self::DEFAULT_RECEIVAL_DAYS
            : max(self::DEFAULT_RECEIVAL_DAYS, (int) round((float) $average));
    }

}
