<?php

namespace App\Domain\Financial\Models;

use App\Domain\Financial\Enums\PaymentMethod;
use App\Domain\Financial\Enums\PaymentStatus;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Payment extends Model
{
    use HasUuid, BelongsToAcademy, SoftDeletes, Auditable;

    protected $fillable = [
        'academy_id',
        'branch_id',
        'cash_session_id',
        'invoice_id',
        'reference',
        'direction',
        'method',
        'status',
        'payer_type',
        'payer_id',
        'amount',
        'currency',
        'payment_date',
        'confirmed_at',
        'failed_at',
        'notes',
        'gateway_data',
        'metadata',
        'received_by',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'method' => PaymentMethod::class,
            'status' => PaymentStatus::class,
            'amount' => 'integer',
            'payment_date' => 'date',
            'confirmed_at' => 'datetime',
            'failed_at' => 'datetime',
            'gateway_data' => 'array',
            'metadata' => 'array',
        ];
    }

    public function invoice(): BelongsTo
    {
        return $this->belongsTo(Invoice::class);
    }

    public function payer(): MorphTo
    {
        return $this->morphTo();
    }

    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class);
    }

    public function receiver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'received_by');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\Branch::class);
    }

    public function cashSession(): BelongsTo
    {
        return $this->belongsTo(CashSession::class);
    }

    public function processedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'received_by');
    }

    public function isInbound(): bool
    {
        return $this->direction === 'inbound';
    }

    public function isConfirmed(): bool
    {
        return $this->status === PaymentStatus::Confirmed;
    }

    public function isFinancialAudit(): bool
    {
        return true;
    }
}
