<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\AccountTransaction;
use App\Models\Finance\CustomerAccount;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CustomerAccountController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CustomerAccount::query()->with(['customer']);
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function show(CustomerAccount $customerAccount): JsonResponse
    {
        return $this->success($customerAccount->load(['customer', 'transactions']));
    }

    public function recharge(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'amount' => 'required|numeric|min:0.01',
            'pay_method' => 'nullable|integer|in:1,2,3,4',
            'description' => 'nullable|string|max:255',
        ]);

        return DB::transaction(function () use ($validated) {
            $account = CustomerAccount::firstOrCreate(
                ['customer_id' => $validated['customer_id'], 'store_id' => auth()->user()->store_id ?? 0],
                ['cash_balance' => 0, 'card_balance' => 0, 'points' => 0]
            );

            $account->increment('cash_balance', $validated['amount']);
            $account->refresh();

            AccountTransaction::create([
                'store_id' => $account->store_id,
                'customer_account_id' => $account->id,
                'customer_id' => $validated['customer_id'],
                'type' => 1,
                'amount' => $validated['amount'],
                'balance_after' => $account->cash_balance,
                'description' => $validated['description'] ?? '账户充值',
                'operator_id' => auth()->id(),
            ]);

            return $this->success($account);
        });
    }
}
