<?php

namespace BitApps\PiPro\src\Integrations\FluentCart\Services;

use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\PiPro\src\Integrations\FluentCart\FluentCartHelper;
use FluentCart\App\Models\OrderTransaction;

if (!\defined('ABSPATH')) {
    exit;
}

final class OrderTransactionService
{
    private $nodeInfoProvider;

    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function getAllTransaction(): array
    {
        if ($validationResponse = FluentCartHelper::validateClassExistence('order_transaction')) {
            return $validationResponse;
        }

        $transactions = OrderTransaction::all();
        $data = ['transactions' => FluentCartHelper::prepareData($transactions)];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getTransactionById(): array
    {
        if ($validationError = FluentCartHelper::validateClassExistence('order_transaction')) {
            return $validationError;
        }

        $fieldMappings = $this->nodeInfoProvider->getFieldMapData();
        $rules = ['id' => ['required', 'integer']];

        if ($validationError = FluentCartHelper::validateFieldMap($fieldMappings, $rules)) {
            return $validationError;
        }


        $transaction = OrderTransaction::find($fieldMappings['id']);

        if (!$transaction) {
            return [
                'response'    => __('Transaction not found.', 'bit-pi'),
                'payload'     => [],
                'status_code' => 404
            ];
        }

        return [
            'response'    => FluentCartHelper::prepareData($transaction),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getRefundTransactions(): array
    {
        if ($validationResponse = FluentCartHelper::validateClassExistence('order_transaction')) {
            return $validationResponse;
        }

        $transactions = OrderTransaction::whereIn('transaction_type', ['refund', 'partial_refund'])
            ->get();

        $data = ['transactions' => FluentCartHelper::prepareData($transactions)];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    public function getSubscriptionTransactions(): array
    {
        if ($validationResponse = FluentCartHelper::validateClassExistence('order_transaction')) {
            return $validationResponse;
        }

        $transactions = OrderTransaction::whereNotNull('subscription_id')->get();

        $data = ['transactions' => FluentCartHelper::prepareData($transactions)];

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }
}
