<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Http\Controllers\Controller;
use App\Services\BackflowService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Carbon\Carbon;

class Backflow extends Controller
{
    function grant(): JsonResponse
    {
        DB::beginTransaction();
        try {
            $params = request()->validate(['id' => ['required', 'integer', 'min:1']]);
            BackflowService::grant($params['id']);
            DB::commit();
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success();
    }

    function index(): JsonResponse
    {
        try {
            $params = request()->validate([
                'page' => ['required', 'integer', 'min:1'],
                'limit' => ['required', 'integer', 'min:1'],
                'member_id' => ['nullable', 'string'],
                'first_name' => ['nullable'],
                'date' => ['nullable', 'date_format:Y-m'],
                'username' => ['nullable', 'string'],
            ]);
            $params['page'] = request()->input('page', 1);
            $params['limit'] = request()->input('limit', 10);
            $result = BackflowService::paginate($params);
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getMessage());
        }
        return $this->success($result);
    }
}