<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Currency;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
use Inertia\Response;

class CurrencyController extends Controller
{
    public function index(): Response
    {
        $currencies = Currency::query()->orderBy('code')->get();

        return Inertia::render('Admin/Currencies/Index', [
            'currencies' => $currencies,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'code' => ['required', 'string', 'size:3', 'unique:currencies,code'],
            'symbol' => ['required', 'string', 'max:5'],
            'name' => ['required', 'string', 'max:255'],
            'decimal_places' => ['required', 'integer', 'min:0', 'max:4'],
            'exchange_rate' => ['required', 'numeric', 'min:0.000001'],
            'is_base' => ['boolean'],
            'is_enabled' => ['boolean'],
        ]);

        $validated['code'] = strtoupper($validated['code']);

        // If setting as base currency, unset other base currencies
        if ($validated['is_base'] ?? false) {
            Currency::query()->where('is_base', true)->update(['is_base' => false]);
            $validated['exchange_rate'] = 1.000000;
        }

        $currency = Currency::create($validated);

        Cache::forget('currencies:enabled');
        Cache::forget('currencies:base');

        AuditLog::create([
            'admin_id' => $request->user()?->id,
            'action' => 'create_currency',
            'resource_type' => 'currency',
            'resource_id' => $currency->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'changes' => $validated,
        ]);

        return redirect()->route('admin.currencies.index')
            ->with('success', "Currency {$currency->code} has been created.");
    }

    public function update(Request $request, Currency $currency): RedirectResponse
    {
        $validated = $request->validate([
            'symbol' => ['required', 'string', 'max:5'],
            'name' => ['required', 'string', 'max:255'],
            'decimal_places' => ['required', 'integer', 'min:0', 'max:4'],
            'exchange_rate' => ['required', 'numeric', 'min:0.000001'],
            'is_base' => ['boolean'],
            'is_enabled' => ['boolean'],
        ]);

        // If setting as base currency, unset other base currencies
        if ($validated['is_base'] ?? false) {
            Currency::query()->where('is_base', true)->where('id', '!=', $currency->id)->update(['is_base' => false]);
            $validated['exchange_rate'] = 1.000000;
        }

        $currency->update($validated);

        Cache::forget('currencies:enabled');
        Cache::forget('currencies:base');

        AuditLog::create([
            'admin_id' => $request->user()?->id,
            'action' => 'update_currency',
            'resource_type' => 'currency',
            'resource_id' => $currency->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'changes' => $validated,
        ]);

        return redirect()->route('admin.currencies.index')
            ->with('success', "Currency {$currency->code} has been updated.");
    }

    public function destroy(Request $request, Currency $currency): RedirectResponse
    {
        if ($currency->is_base) {
            return redirect()->back()->with('error', 'Cannot delete the base currency.');
        }

        $code = $currency->code;
        $currency->delete();

        Cache::forget('currencies:enabled');
        Cache::forget('currencies:base');

        AuditLog::create([
            'admin_id' => $request->user()?->id,
            'action' => 'delete_currency',
            'resource_type' => 'currency',
            'resource_id' => 0,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'changes' => ['code' => $code],
        ]);

        return redirect()->route('admin.currencies.index')
            ->with('success', "Currency {$code} has been deleted.");
    }

    public function syncRates(Request $request): RedirectResponse
    {
        Artisan::call('currencies:sync-rates');

        AuditLog::create([
            'admin_id' => $request->user()?->id,
            'action' => 'sync_exchange_rates',
            'resource_type' => 'currency',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return redirect()->route('admin.currencies.index')
            ->with('success', 'Exchange rates have been synced.');
    }
}
