<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * @property int $id
 * @property int $schedule_id
 * @property int $client_id
 * @property int|null $provider_id
 * @property int|null $client_payment_method_id
 * @property string $gateway_provider
 * @property string|null $gateway_entity_reference
 * @property string|null $gateway_entity_label
 * @property string|null $gateway_operation_reference
 * @property string|null $gateway_operation_label
 * @property string $payment_method
 * @property \App\Enums\PaymentStatusEnum $status
 * @property numeric $gross_amount Valor bruto cobrado do cliente.
 * @property numeric $gateway_fee_amount Taxa cobrada pelo gateway nesta cobranca.
 * @property numeric $platform_fee_amount Taxa da plataforma (regra interna), sem impacto na formula de net_amount.
 * @property numeric $net_amount Valor liquido apos taxa do gateway: net_amount = gross_amount - gateway_fee_amount.
 * @property string $currency
 * @property int $installments
 * @property \Illuminate\Support\Carbon|null $authorized_at
 * @property \Illuminate\Support\Carbon|null $paid_at
 * @property \Illuminate\Support\Carbon|null $failed_at
 * @property \Illuminate\Support\Carbon|null $cancelled_at
 * @property \Illuminate\Support\Carbon|null $expires_at
 * @property string|null $failure_code
 * @property string|null $failure_message
 * @property array<array-key, mixed>|null $gateway_payload
 * @property array<array-key, mixed>|null $metadata
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property string|null $gateway_code
 * @property string|null $idempotency_key
 * @property-read \App\Models\Client $client
 * @property-read \App\Models\ClientPaymentMethod|null $clientPaymentMethod
 * @property-read \App\Models\Provider|null $provider
 * @property-read \App\Models\Schedule $schedule
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\PaymentSplit> $splits
 * @property-read int|null $splits_count
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Webhook> $webhooks
 * @property-read int|null $webhooks_count
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereAuthorizedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereCancelledAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereClientId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereClientPaymentMethodId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereCurrency($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereExpiresAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereFailedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereFailureCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereFailureMessage($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayEntityLabel($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayEntityReference($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayFeeAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayOperationLabel($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayOperationReference($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayPayload($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGatewayProvider($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereGrossAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereIdempotencyKey($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereInstallments($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereMetadata($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereNetAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment wherePaidAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment wherePaymentMethod($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment wherePlatformFeeAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereProviderId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereScheduleId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment withTrashed(bool $withTrashed = true)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Payment withoutTrashed()
 * @mixin \Eloquent
 */
class Payment extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'payments';

    protected $fillable = [
        'schedule_id',
        'service_package_id',
        'client_id',
        'provider_id',
        'client_payment_method_id',
        'gateway_provider',
        'gateway_code',
        'idempotency_key',
        'gateway_entity_reference',
        'gateway_entity_label',
        'gateway_operation_reference',
        'gateway_operation_label',
        'payment_method',
        'status',
        'gross_amount',
        'gateway_fee_amount',
        'platform_fee_amount',
        'net_amount',
        'currency',
        'installments',
        'authorized_at',
        'paid_at',
        'failed_at',
        'cancelled_at',
        'expires_at',
        'failure_code',
        'failure_message',
        'gateway_payload',
        'metadata',
    ];

    protected $casts = [
        'gross_amount'        => 'decimal:2',
        'gateway_fee_amount'  => 'decimal:2',
        'platform_fee_amount' => 'decimal:2',
        'net_amount'          => 'decimal:2',
        'installments'        => 'integer',
        'status'              => \App\Enums\PaymentStatusEnum::class,
        'authorized_at'       => 'datetime',
        'paid_at'             => 'datetime',
        'failed_at'           => 'datetime',
        'cancelled_at'        => 'datetime',
        'expires_at'          => 'datetime',
        'gateway_payload'     => 'array',
        'metadata'            => 'array',
        'created_at'          => 'datetime',
        'updated_at'          => 'datetime',
        'deleted_at'          => 'datetime',
    ];

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function provider()
    {
        return $this->belongsTo(Provider::class);
    }

    public function schedule()
    {
        return $this->belongsTo(Schedule::class);
    }

    public function servicePackage()
    {
        return $this->belongsTo(ServicePackage::class);
    }

    //

    public function clientPaymentMethod()
    {
        return $this->belongsTo(ClientPaymentMethod::class);
    }

    public function splits()
    {
        return $this->hasMany(PaymentSplit::class);
    }

    public function webhooks()
    {
        return $this->hasMany(Webhook::class);
    }

    //

    public function ensureGatewayCode(): string
    {
        if (! empty($this->gateway_code)) {
            return $this->gateway_code;
        }

        $code = 'payment-'.(string) \Illuminate\Support\Str::uuid();

        $this->forceFill(['gateway_code' => $code])->save();

        return $code;
    }

    public function pixData(): ?array
    {
        if ($this->payment_method !== 'pix') {
            return null;
        }

        $charge = data_get($this->gateway_payload, 'charges.0', []);

        $transaction = data_get($charge, 'last_transaction', []);

        $expiresAt = data_get($charge, 'expires_at')
            ?? data_get($transaction, 'expires_at')
            ?? $this->expires_at?->toISOString();

        $qrCode    = data_get($transaction, 'qr_code');
        $qrCodeUrl = data_get($transaction, 'qr_code_url');
        $status    = data_get($transaction, 'status');

        return [
            'qr_code'     => $qrCode,
            'qr_code_url' => $qrCodeUrl,
            'expires_at'  => $expiresAt,
            'status'      => $status,
        ];
    }
}
