<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\AuditService;
use App\Services\SystemBackupService;
use App\Services\SystemResetService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule;
use Illuminate\View\View;
use RuntimeException;
use Throwable;

class SystemResetController extends Controller
{
    private const CONFIRMATION_PHRASE = 'RESET EVERYTHING';

    public function index(Request $request, SystemBackupService $backups): View
    {
        $this->authorizeSuperAdministrator($request);

        return view('admin.settings.system-reset', [
            'confirmationPhrase' => self::CONFIRMATION_PHRASE,
            'summary' => [
                'customers' => $this->tableCount('customers'),
                'loans' => $this->tableCount('loans'),
                'branches' => $this->tableCount('branches'),
                'staff' => $this->tableCount('users'),
                'audit_logs' => $this->tableCount('audit_logs'),
                'backups' => $backups->summary(),
            ],
        ]);
    }

    public function reset(Request $request, SystemResetService $resetter): RedirectResponse
    {
        $administrator = $this->authorizeSuperAdministrator($request);

        $data = $request->validate([
            'current_password' => ['required', 'string'],
            'confirmation_phrase' => ['required', 'string', Rule::in([self::CONFIRMATION_PHRASE])],
            'understand' => ['accepted'],
        ], [
            'confirmation_phrase.in' => 'Type '.self::CONFIRMATION_PHRASE.' exactly to continue.',
            'understand.accepted' => 'You must confirm that you understand the reset is destructive.',
        ]);

        if (! Hash::check((string) $data['current_password'], (string) $administrator->getRawOriginal('password'))) {
            return back()->withErrors([
                'current_password' => 'The password you entered is incorrect.',
            ]);
        }

        try {
            $result = $resetter->reset($administrator);
        } catch (Throwable $exception) {
            report($exception);

            $message = $exception instanceof RuntimeException
                ? $exception->getMessage()
                : 'Factory reset failed unexpectedly. No further reset action was attempted.';

            return back()->with('error', $message);
        }

        Auth::login($result['administrator']);
        $request->session()->regenerate();

        AuditService::record('system.factory_reset.completed', $result['administrator'], [], [
            'backup_filename' => $result['backup']['filename'] ?? null,
            'backup_type' => $result['backup']['type'] ?? null,
            'preserved_administrator_id' => $result['administrator']->id,
        ]);

        return redirect()
            ->route('dashboard')
            ->with('success', 'System factory reset completed. A recovery backup was preserved in System Backups.');
    }

    private function authorizeSuperAdministrator(Request $request)
    {
        $user = $request->user();
        abort_unless($user && $user->hasRole('super-administrator'), 403);

        return $user;
    }

    private function tableCount(string $table): int
    {
        return Schema::hasTable($table) ? (int) DB::table($table)->count() : 0;
    }
}
