<?php

namespace App\Support;

use App\Models\MoraqebatChecklist;

class MoraqebatChecklistCondition
{
    /**
     * @param  array<string, mixed>|MoraqebatChecklist  $data
     */
    public static function score(array|MoraqebatChecklist $data): int
    {
        $machineState = $data instanceof MoraqebatChecklist
            ? $data->machine_state
            : (string) ($data['machine_state'] ?? '');

        $isOilingChecked = (bool) ($data instanceof MoraqebatChecklist
            ? $data->is_oiling_checked
            : ($data['is_oiling_checked'] ?? false));

        $isCleanlinessChecked = (bool) ($data instanceof MoraqebatChecklist
            ? $data->is_cleanliness_checked
            : ($data['is_cleanliness_checked'] ?? false));

        $isAbnormalNoise = (bool) ($data instanceof MoraqebatChecklist
            ? $data->is_abnormal_noise
            : ($data['is_abnormal_noise'] ?? false));

        $isObservedIssue = (bool) ($data instanceof MoraqebatChecklist
            ? $data->is_observed_issue
            : ($data['is_observed_issue'] ?? false));

        $score = $machineState === MoraqebatMachineState::FINE ? 100 : 0;

        if ($isOilingChecked) {
            $score += 5;
        }

        if ($isCleanlinessChecked) {
            $score += 5;
        }

        if ($isAbnormalNoise) {
            $score -= 5;
        }

        if ($isObservedIssue) {
            $score -= 5;
        }

        return $score;
    }

    public static function resolveTrend(int $currentScore, ?MoraqebatChecklist $previous): string
    {
        if ($previous === null) {
            return MoraqebatConditionTrend::FIRST;
        }

        $previousScore = $previous->condition_score ?? self::score($previous);

        if ($currentScore > $previousScore) {
            return MoraqebatConditionTrend::UP;
        }

        if ($currentScore < $previousScore) {
            return MoraqebatConditionTrend::DOWN;
        }

        return MoraqebatConditionTrend::SAME;
    }

    public static function previousForMachine(int $machineId, ?int $excludeChecklistId = null): ?MoraqebatChecklist
    {
        return MoraqebatChecklist::query()
            ->where('moraqebat_machine_id', $machineId)
            ->when($excludeChecklistId !== null, fn ($query) => $query->where('id', '!=', $excludeChecklistId))
            ->orderByDesc('inspection_date')
            ->orderByDesc('id')
            ->first();
    }
}
