<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuthorizationQueue;
use App\Models\Loan;
use App\Services\AuditService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class OperationsController extends Controller
{
    public function __construct(
        protected AuditService $auditService,
    ) {}

    public function index(): View
    {
        $pendingItems = AuthorizationQueue::query()
            ->with(['inputer', 'authorizer'])
            ->where('status', 'pending')
            ->orderByRaw("FIELD(priority, 'critical', 'high', 'normal', 'low')")
            ->latest()
            ->paginate(20);

        return view('admin.operations.index', compact('pendingItems'));
    }

    public function approve(AuthorizationQueue $item): RedirectResponse
    {
        if ($item->status !== 'pending') {
            return back()->withErrors(['authorization' => 'This item has already been processed.']);
        }

        $user = auth()->user();

        if (! $user->isAuthorizer()) {
            return back()->withErrors(['authorization' => 'You are not authorized to approve transactions.']);
        }

        if ($item->inputer_id === $user->id) {
            return back()->withErrors(['authorization' => 'Inputer cannot authorize their own transaction.']);
        }

        $old = $item->toArray();

        $item->update([
            'status' => 'approved',
            'authorizer_id' => $user->id,
            'decided_at' => now(),
        ]);

        if ($item->module === 'loans' && $item->action === 'disburse' && $item->record_type === 'loan') {
            $loan = Loan::query()->find($item->record_id);

            if ($loan) {
                $loanOld = $loan->toArray();

                $loan->update([
                    'status' => 'active',
                    'disbursed_amount' => $loan->disbursed_amount ?? $loan->principal - $loan->processing_fee,
                    'outstanding_principal' => $loan->principal,
                    'disbursement_date' => now()->toDateString(),
                    'disbursed_by' => $user->id,
                ]);

                $this->auditService->log('disburse', 'loans', 'loan', $loan->id, $loanOld, $loan->fresh()->toArray());
            }
        }

        $this->auditService->log('approve', 'operations', 'authorization_queue', $item->id, $old, $item->fresh()->toArray());

        return back()->with('success', 'Authorization approved successfully.');
    }

    public function reject(Request $request, AuthorizationQueue $item): RedirectResponse
    {
        if ($item->status !== 'pending') {
            return back()->withErrors(['authorization' => 'This item has already been processed.']);
        }

        $user = auth()->user();

        if (! $user->isAuthorizer()) {
            return back()->withErrors(['authorization' => 'You are not authorized to reject transactions.']);
        }

        if ($item->inputer_id === $user->id) {
            return back()->withErrors(['authorization' => 'Inputer cannot reject their own transaction.']);
        }

        $validated = $request->validate([
            'remarks' => ['required', 'string', 'max:1000'],
        ]);

        $old = $item->toArray();

        $item->update([
            'status' => 'rejected',
            'authorizer_id' => $user->id,
            'remarks' => $validated['remarks'],
            'decided_at' => now(),
        ]);

        $this->auditService->log('reject', 'operations', 'authorization_queue', $item->id, $old, $item->fresh()->toArray());

        return back()->with('success', 'Authorization rejected.');
    }
}
