<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

final class MerchantApprovalController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->input('status', 'pending');
        $query = Merchant::query()->latest('id');

        if ($status !== 'all') {
            $query->where('status', $status);
        }

        return ApiResponse::success($query->paginate(min(100, (int) $request->input('per_page', 20))));
    }

    public function approve(Merchant $merchant)
    {
        $merchant->forceFill(['status' => 'active'])->save();

        return ApiResponse::success($merchant->fresh());
    }

    public function decline(Request $request, Merchant $merchant)
    {
        $request->validate([
            'reason' => 'sometimes|nullable|string|max:500',
        ]);

        $merchant->forceFill(['status' => 'rejected'])->save();

        return ApiResponse::success([
            'merchant' => $merchant->fresh(),
            'reason' => $request->input('reason'),
        ]);
    }
}