<?php

namespace App\Support;

use Illuminate\Support\Facades\File;

/**
 * Resolves the Firebase service-account JSON path for FCM.
 *
 * Prefers FIREBASE_CREDENTIALS / config, then known storage paths.
 * Accepts both lowercase and legacy "Kiyohr-..." filenames (Windows vs Linux).
 */
final class FirebaseCredentials
{
    public const DEFAULT_RELATIVE = 'app/firebase/kiyohr-service-account.json';

    public const LEGACY_RELATIVE = 'app/firebase/Kiyohr-service-account.json';

    /**
     * Absolute path to a readable credentials file, or null if none found.
     */
    public static function path(): ?string
    {
        $candidates = [];

        $configured = config('firebase.projects.app.credentials') ?: env('FIREBASE_CREDENTIALS') ?: env('GOOGLE_APPLICATION_CREDENTIALS');
        if (is_string($configured) && $configured !== '') {
            $candidates[] = self::normalize($configured);
        }

        $candidates[] = storage_path(self::DEFAULT_RELATIVE);
        $candidates[] = storage_path(self::LEGACY_RELATIVE);

        $seen = [];
        foreach ($candidates as $path) {
            if ($path === '' || isset($seen[$path])) {
                continue;
            }
            $seen[$path] = true;

            if (File::isFile($path)) {
                return $path;
            }

            // Case-insensitive directory scan (helps when .env casing ≠ disk on Linux).
            $resolved = self::resolveCaseInsensitive($path);
            if ($resolved !== null) {
                return $resolved;
            }
        }

        return null;
    }

    public static function isConfigured(): bool
    {
        return self::path() !== null;
    }

    protected static function normalize(string $path): string
    {
        $path = trim($path);
        if ($path === '') {
            return '';
        }

        // Absolute Windows (C:\...) or Unix (/...) paths.
        if (preg_match('#^[a-zA-Z]:[\\\\/]#', $path) === 1 || str_starts_with($path, '/')) {
            return $path;
        }

        if (str_starts_with($path, 'storage/')) {
            return base_path($path);
        }

        if (str_starts_with($path, 'app/firebase/')) {
            return storage_path($path);
        }

        return base_path($path);
    }

    protected static function resolveCaseInsensitive(string $path): ?string
    {
        $dir = dirname($path);
        $wanted = strtolower(basename($path));

        if (! File::isDirectory($dir)) {
            return null;
        }

        foreach (File::files($dir) as $file) {
            if (strtolower($file->getFilename()) === $wanted) {
                return $file->getPathname();
            }
        }

        return null;
    }
}
