<?php

namespace App\Installer\Services;

use App\Core\Services\RoleService;
use App\Core\Services\UserService;
use App\Models\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;

/**
 * Installation Manager Service
 * Manages the overall installation process
 */
class InstallationManager
{
    public function __construct(
        private UserService $userService,
        private RoleService $roleService
    ) {}

    /**
     * Check if application is installed
     */
    public function isInstalled(): bool
    {
        $installedFile = storage_path('app/.installed');

        return file_exists($installedFile);
    }

    /**
     * Mark application as installed
     */
    public function markAsInstalled(): bool
    {
        try {
            $installedFile = storage_path('app/.installed');
            $content = [
                'installed_at' => now()->toDateTimeString(),
                'version' => config('app.version', '1.0.0'),
                'installer_hash' => $this->generateInstallerHash(),
            ];

            File::put($installedFile, json_encode($content));

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * Create admin user
     */
    public function createAdminUser(string $email, string $password): User
    {
        $adminRole = $this->roleService->getBySlug('admin');

        if (! $adminRole) {
            // Create admin role if it doesn't exist
            $adminRole = $this->roleService->create([
                'name' => 'Administrator',
                'slug' => 'admin',
                'description' => 'Full system access',
                'is_active' => true,
            ]);
        }

        $user = $this->userService->create([
            'name' => 'Administrator',
            'email' => $email,
            'password' => $password,
            'role_id' => $adminRole->id,
        ]);

        return $user;
    }

    /**
     * Import demo data
     */
    public function importDemoData(): bool
    {
        try {
            // Run all seeders to import demo data
            \Illuminate\Support\Facades\Artisan::call('db:seed', [
                '--class' => 'DatabaseSeeder',
                '--force' => true,
            ]);

            return true;
        } catch (\Exception $e) {
            \Log::error('Demo data import failed: '.$e->getMessage());

            return false;
        }
    }

    /**
     * Generate installer hash for security
     */
    private function generateInstallerHash(): string
    {
        $installerPath = app_path('Installer');
        $files = File::allFiles($installerPath);

        $content = '';
        foreach ($files as $file) {
            $content .= $file->getContents();
        }

        return hash('sha256', $content.config('app.key'));
    }

    /**
     * Verify installer integrity
     */
    public function verifyInstallerIntegrity(): bool
    {
        if (! $this->isInstalled()) {
            return true; // Not installed yet, allow access
        }

        $installedFile = storage_path('app/.installed');
        if (! file_exists($installedFile)) {
            return false;
        }

        $data = json_decode(file_get_contents($installedFile), true);
        $storedHash = $data['installer_hash'] ?? null;

        if (! $storedHash) {
            return false;
        }

        $currentHash = $this->generateInstallerHash();

        return hash_equals($storedHash, $currentHash);
    }
}
