<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\UserWalletRecord;
use Webman\Http\Request;
use support\Response;

class Wallet extends MobileBase
{
    public function recordList(Request $request): Response
    {
        $response = $this->initializeMobile($request);
        if ($response !== null) {
            return $response;
        }
        $type = trim((string) $request->input('type', 'all'));
        $page = $this->intValue($request->input('page', 1), 1);
        $pageSize = $this->intValue($request->input('page_size', 20), 20);

        $query = UserWalletRecord::where('user_id', $this->auth->id)->order('id', 'desc');
        if ($type !== '' && $type !== 'all') {
            $query->where('biz_type', $type);
        }
        $paginate = $query->paginate([
            'page' => $page,
            'list_rows' => $pageSize,
        ]);
        $list = [];
        foreach ($paginate->items() as $row) {
            $list[] = [
                'record_id' => $row->id,
                'biz_type' => $row->biz_type,
                'direction' => $row->direction,
                'amount' => $row->amount,
                'balance_before' => $row->balance_before,
                'balance_after' => $row->balance_after,
                'ref_type' => $row->ref_type,
                'ref_id' => $row->ref_id,
                'create_time' => $row->create_time,
            ];
        }
        return $this->mobileSuccess([
            'list' => $list,
            'pagination' => [
                'page' => $paginate->currentPage(),
                'page_size' => $paginate->listRows(),
                'total' => $paginate->total(),
            ],
        ]);
    }

    private function intValue($value, int $default): int
    {
        $result = filter_var($value, FILTER_VALIDATE_INT);
        if ($result === false) {
            return $default;
        }
        return $result;
    }
}

