<?php

namespace App\Support;

use App\Models\MoraqebatChecklist;
use App\Models\MoraqebatChecklistBatch;
use App\Models\MoraqebatMachine;

class MoraqebatDashboard
{
    /**
     * @return array<string, mixed>|null
     */
    public static function overview(): ?array
    {
        if (! auth()->user()?->can('moraqebat-checklists.view')) {
            return null;
        }

        $activeMachines = MoraqebatMachine::query()
            ->where('is_active', true)
            ->count();

        $latestBatch = MoraqebatChecklistBatch::query()
            ->orderByDesc('inspection_date')
            ->orderByDesc('id')
            ->first();

        if ($latestBatch !== null) {
            $summary = MoraqebatChecklistSubmissionSummary::serializeBatch($latestBatch);

            return self::buildPayload($activeMachines, $summary);
        }

        $latestChecklist = MoraqebatChecklist::query()
            ->orderByDesc('inspection_date')
            ->orderByDesc('id')
            ->first();

        if ($latestChecklist === null) {
            return [
                'has_checklist' => false,
                'active_machines' => $activeMachines,
            ];
        }

        $summary = MoraqebatChecklistSubmissionSummary::serializeLegacyChecklist($latestChecklist);

        return self::buildPayload($activeMachines, $summary);
    }

    /**
     * @param  array<string, mixed>  $summary
     * @return array<string, mixed>
     */
    private static function buildPayload(int $activeMachines, array $summary): array
    {
        return [
            'has_checklist' => true,
            'active_machines' => $activeMachines,
            'checked_machines' => $summary['machine_count'],
            'inspection_date' => $summary['inspection_date'],
            'staff_name' => $summary['staff_name'],
            'fine_count' => $summary['fine_count'],
            'not_fine_count' => $summary['not_fine_count'],
            'trends' => $summary['trends'],
            'technical_officer' => $summary['technical_officer'],
            'latest_checklist_id' => $summary['checklist_id'],
        ];
    }
}
