<?php

namespace App\Modules\Sales\Models;

use App\Modules\Admin\Tenancy\Traits\BelongsToTenant;
use App\Support\SystemReferenceGenerator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SalesOrder extends Model
{
    use BelongsToTenant;

    protected $table = 'sales_orders';

    protected $fillable = ['tenant_id', 'status', 'order_number', 'correlation_id'];

    protected function casts(): array
    {
        return [
            'correlation_id' => 'string',
        ];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(SalesOrderLine::class, 'sales_order_id');
    }

    public function returns(): HasMany
    {
        return $this->hasMany(SalesReturn::class, 'sales_order_id');
    }

    public function displayOrderNumber(): string
    {
        if ($this->order_number !== null && $this->order_number !== '') {
            return $this->order_number;
        }

        return SystemReferenceGenerator::format(
            SystemReferenceGenerator::SALES_ORDER,
            (int) $this->getKey(),
        );
    }
}
