<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\AdminActivityLogger;
use App\Services\RepairToolService;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class RepairToolController extends Controller
{
    public function index(): View
    {
        return view('admin.repair-tools');
    }

    public function recalculateWallet(
        Request $request,
        RepairToolService $repairToolService,
        AdminActivityLogger $logger
    ): RedirectResponse
    {
        $repairToolService->recalculateWallet($request->input('user_id'));
        $logger->log('repair.recalculate_wallet', null, null, ['user_id' => $request->input('user_id')]);

        return back()->with('status', 'Wallet recalculation triggered.');
    }

    public function rebuildCarry(RepairToolService $repairToolService, AdminActivityLogger $logger): RedirectResponse
    {
        $repairToolService->rebuildCarry();
        $logger->log('repair.rebuild_carry');

        return back()->with('status', 'Carry forward rebuild completed.');
    }

    public function fixTree(
        Request $request,
        RepairToolService $repairToolService,
        AdminActivityLogger $logger
    ): RedirectResponse
    {
        $repairToolService->fixTree($request->input('user_id'));
        $logger->log('repair.fix_tree', null, null, ['user_id' => $request->input('user_id')]);

        return back()->with('status', 'Tree rebuild completed.');
    }

    public function retryPayouts(
        Request $request,
        RepairToolService $repairToolService,
        AdminActivityLogger $logger
    ): RedirectResponse
    {
        $repairToolService->retryFailedPayouts($request->input('batch_id'));
        $logger->log('repair.retry_payouts', null, null, ['batch_id' => $request->input('batch_id')]);

        return back()->with('status', 'Payout retry job dispatched.');
    }

    public function retryWebhooks(
        Request $request,
        RepairToolService $repairToolService,
        AdminActivityLogger $logger
    ): RedirectResponse
    {
        $repairToolService->retryWebhooks($request->input('gateway'));
        $logger->log('repair.retry_webhooks', null, null, ['gateway' => $request->input('gateway')]);

        return back()->with('status', 'Webhook retry job dispatched.');
    }

    public function enableMaintenance(AdminActivityLogger $logger): RedirectResponse
    {
        Artisan::call('down');
        $logger->log('maintenance.enable');

        return back()->with('status', 'Maintenance mode enabled.');
    }

    public function disableMaintenance(AdminActivityLogger $logger): RedirectResponse
    {
        Artisan::call('up');
        $logger->log('maintenance.disable');

        return back()->with('status', 'Maintenance mode disabled.');
    }
}
