<?php

namespace App\Services\Integrity;

use App\Contracts\CoreHashValidatorContract;
use App\Support\IntegrityManifestStore;
use Illuminate\Support\Facades\File;

class CoreHashValidator implements CoreHashValidatorContract
{
    /**
     * @return array{valid: bool, status: string, message: ?string, failures: list<string>}
     */
    public function validate(): array
    {
        $manifest = IntegrityManifestStore::read();

        if ($manifest === null || ! isset($manifest['files']) || ! is_array($manifest['files'])) {
            return [
                'valid' => true,
                'status' => 'unknown',
                'message' => null,
                'failures' => [],
            ];
        }

        $failures = [];

        foreach ($manifest['files'] as $relativePath => $expectedHash) {
            if (! is_string($relativePath) || ! is_string($expectedHash)) {
                continue;
            }

            $absolutePath = base_path(str_replace('/', DIRECTORY_SEPARATOR, $relativePath));

            if (! File::isFile($absolutePath)) {
                $failures[] = $relativePath;

                continue;
            }

            $actualHash = hash_file('sha256', $absolutePath);

            if (! hash_equals($expectedHash, $actualHash)) {
                $failures[] = $relativePath;
            }
        }

        if ($failures !== []) {
            return [
                'valid' => false,
                'status' => 'tampered',
                'message' => 'Core application files were modified. Marketplace access, updates, and platform services are disabled until you restore the official release.',
                'failures' => array_values($failures),
            ];
        }

        return [
            'valid' => true,
            'status' => 'verified',
            'message' => null,
            'failures' => [],
        ];
    }
}
