<?php

namespace App\Services\Pagarme;

use App\Models\Provider;
use PagarmeApiSDKLib\Authentication\BasicAuthCredentialsBuilder;
use PagarmeApiSDKLib\Models\Builders\CreateBankAccountRequestBuilder;
use PagarmeApiSDKLib\Models\Builders\CreateRecipientRequestBuilder;
use PagarmeApiSDKLib\Models\Builders\CreateTransferSettingsRequestBuilder;
use PagarmeApiSDKLib\Models\Builders\UpdateAutomaticAnticipationSettingsRequestBuilder;
use PagarmeApiSDKLib\PagarmeApiSDKClient;
use PagarmeApiSDKLib\PagarmeApiSDKClientBuilder;

class PagarmeRecipientService
{
    private ?PagarmeApiSDKClient $client = null;

    public function createRecipientForProvider(Provider $provider, array $data): string
    {
        if (!empty($provider->recipient_id)) {
            return $provider->recipient_id;
        }

        $client = $this->client();
        $bankAccountData = $data['recipient_default_bank_account'];
        $metadata = $data['recipient_metadata'] ?? [];
        $paymentMode = $data['recipient_payment_mode'];

        $bankAccount = CreateBankAccountRequestBuilder::init(
            $bankAccountData['holder_name'],
            $bankAccountData['holder_type'],
            $bankAccountData['holder_document'],
            $bankAccountData['bank'],
            $bankAccountData['branch_number'],
            $bankAccountData['account_number'],
            $bankAccountData['account_check_digit'],
            $bankAccountData['type'],
            $bankAccountData['metadata'] ?? []
        )
            ->branchCheckDigit($bankAccountData['branch_check_digit'] ?? null)
            ->pixKey($bankAccountData['pix_key'] ?? null)
            ->build();

        $recipientRequest = CreateRecipientRequestBuilder::init(
            $bankAccount,
            $metadata,
            $data['recipient_code'],
            $paymentMode
        )
            ->name($data['recipient_name'])
            ->email($data['recipient_email'])
            ->description($data['recipient_description'])
            ->document($data['recipient_document'])
            ->type($data['recipient_type']);

        $recipientTransferSettings = CreateTransferSettingsRequestBuilder::init(false, 'daily', 0)->build();

        $recipientRequest->transferSettings($recipientTransferSettings);

        $recipient = $client->getRecipientsController()->createRecipient(
            $recipientRequest->build(),
            $this->idempotencyKey($provider->id)
        );

        $recipientId = $recipient->getId();
        if (!$recipientId) {
            throw new \RuntimeException('Pagar.me recipient creation returned an empty id.');
        }

        $provider->forceFill([
            'recipient_id' => $recipientId,
            'recipient_name' => $data['recipient_name'],
            'recipient_email' => $data['recipient_email'],
            'recipient_description' => $data['recipient_description'],
            'recipient_document' => $data['recipient_document'],
            'recipient_type' => $data['recipient_type'],
            'recipient_code' => $data['recipient_code'],
            'recipient_payment_mode' => $paymentMode,
            'recipient_default_bank_account' => $bankAccountData,
            'recipient_transfer_settings' => [
                'transfer_enabled' => false,
                'transfer_interval' => 'daily',
                'transfer_day' => 0,
            ],
            'recipient_automatic_anticipation_settings' => [
                'enabled' => false,
            ],
            'recipient_metadata' => $metadata,
        ])->save();

        $this->applyAutomaticAnticipationSettings($provider->id, $recipientId);

        return $recipientId;
    }

    private function applyAutomaticAnticipationSettings(int $providerId, string $recipientId): void
    {
        $request = UpdateAutomaticAnticipationSettingsRequestBuilder::init()
            ->enabled(false)
            ->build();

        $this->client()->getRecipientsController()->updateAutomaticAnticipationSettings(
            $recipientId,
            $request,
            $this->idempotencyKey($providerId, 'auto-anticipation')
        );
    }

    private function client(): PagarmeApiSDKClient
    {
        if ($this->client) {
            return $this->client;
        }

        $secretKey = config('services.pagarme.secret_key');
        if (empty($secretKey)) {
            throw new \RuntimeException('PAGARME_SECRET_KEY is not configured.');
        }

        $serviceRefererName = (string) config('services.pagarme.service_referer_name', config('app.name'));

        $this->client = PagarmeApiSDKClientBuilder::init()
            ->basicAuthCredentials(
                BasicAuthCredentialsBuilder::init($secretKey, '')
            )
            ->serviceRefererName($serviceRefererName)
            ->build();

        return $this->client;
    }

    private function idempotencyKey(int $providerId, string $suffix = 'recipient'): string
    {
        return "provider-{$providerId}-{$suffix}";
    }
}
