<?php

namespace App\Http\Middleware;

use App\Models\Account;
use App\Models\Currency;
use App\Models\UserSetting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserHasDefaults
{
    /**
     * Handle an incoming request.
     *
     * Ensures the authenticated user has default settings and at least one account.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user) {
            // Ensure user has settings
            if (!$user->settings) {
                $idr = Currency::where('code', 'IDR')->first();

                UserSetting::create([
                    'user_id' => $user->id,
                    'default_currency_id' => $idr?->id,
                    'theme' => 'system',
                    'locale' => 'id',
                    'timezone' => 'Asia/Jakarta',
                    'date_format' => 'd/m/Y',
                ]);
            }

            // Ensure user has at least one account
            if ($user->accounts()->count() === 0) {
                $idr = Currency::where('code', 'IDR')->first();

                if ($idr) {
                    Account::create([
                        'user_id' => $user->id,
                        'currency_id' => $idr->id,
                        'name' => 'Uang Tunai',
                        'type' => 'cash',
                        'initial_balance' => 0,
                        'current_balance' => 0,
                        'icon' => 'money-bill',
                        'color' => '#10B981',
                        'sort_order' => 0,
                    ]);
                }
            }
        }

        return $next($request);
    }
}
