<?php

namespace App\Services\System;

use Illuminate\Support\Facades\Schema;

class HealthCheckService
{
    public function check(): array
    {
        $uploadsBase = storage_path('app/uploads');
        $paths = [
            'uploads' => $uploadsBase,
            'uploads/reimbursements' => $uploadsBase . DIRECTORY_SEPARATOR . 'reimbursements',
            'uploads/receipts' => $uploadsBase . DIRECTORY_SEPARATOR . 'receipts',
            'uploads/checks' => $uploadsBase . DIRECTORY_SEPARATOR . 'checks',
            'uploads/early_dismissal_signatures' => $uploadsBase . DIRECTORY_SEPARATOR . 'early_dismissal_signatures',
        ];

        $pathsStatus = [];
        foreach ($paths as $label => $path) {
            $pathsStatus[] = [
                'label' => $label,
                'path' => $path,
                'exists' => is_dir($path),
                'writable' => is_writable($path),
            ];
        }

        $dbChecks = [
            'user_preferences_exists' => Schema::hasTable('user_preferences'),
            'settings_exists' => Schema::hasTable('settings'),
            'migrations_exists' => Schema::hasTable('migrations'),
        ];

        $dbChecks['user_preferences_has_timezone'] = $dbChecks['user_preferences_exists']
            ? Schema::hasColumn('user_preferences', 'timezone')
            : false;

        $dbChecks['settings_has_timezone'] = $dbChecks['settings_exists']
            ? Schema::hasColumn('settings', 'timezone')
            : false;

        $okPaths = array_reduce($pathsStatus, function (bool $carry, array $row) {
            return $carry && $row['exists'] && $row['writable'];
        }, true);

        $okDb = true;
        if ($dbChecks['user_preferences_exists'] && !$dbChecks['user_preferences_has_timezone']) {
            $okDb = false;
        }
        if ($dbChecks['settings_exists'] && !$dbChecks['settings_has_timezone']) {
            $okDb = false;
        }

        return [
            'ok' => $okPaths && $okDb,
            'paths' => $pathsStatus,
            'database' => $dbChecks,
            'write_path' => storage_path(),
            'timestamp' => now()->toIso8601String(),
        ];
    }
}
