<?php

namespace App\Models\Purchasing;

use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Inventory\Grn;
use App\Models\Inventory\SupplierDocument;
use App\Models\Lookups\PaymentTerm;
use App\Models\Lookups\Status;
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\SoftDeletes;
use Illuminate\Support\Str;

class Supplier extends Model
{
    use Auditable, BelongsToTenant, SoftDeletes;

    protected $fillable = [
        'uuid', 'name', 'business_name', 'registration_number', 'tax_number',
        'phone', 'email', 'website', 'payment_terms_id',
        'credit_limit', 'outstanding_balance', 'status_id',
        'is_blacklisted', 'blacklisted_reason', 'blacklisted_at', 'blacklisted_by',
        'notes', 'created_by', 'updated_by', 'deleted_by',
    ];

    protected function casts(): array
    {
        return [
            'credit_limit' => 'decimal:2',
            'outstanding_balance' => 'decimal:2',
            'is_blacklisted' => 'boolean',
            'blacklisted_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $supplier): void {
            if (! $supplier->uuid) {
                $supplier->uuid = (string) Str::ulid();
            }
        });
    }

    public function paymentTerms(): BelongsTo
    {
        return $this->belongsTo(PaymentTerm::class, 'payment_terms_id');
    }

    public function status(): BelongsTo
    {
        return $this->belongsTo(Status::class, 'status_id');
    }

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

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

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

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

    public function ledgers(): HasMany
    {
        return $this->hasMany(SupplierLedger::class)->latest('created_at');
    }

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

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

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

    public function isActive(): bool
    {
        return $this->status?->code === Status::SUPPLIER_ACTIVE;
    }
}
