<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Mtc\MercuryDataModels\Tenant;
use Mtc\MercuryDataModels\User;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class SpecDocument extends Model
{
    use CentralConnection;
    use HasFactory;

    protected $fillable = [
        'tenant_id',
        'title',
        'version',
        'signed_off_at',
        'signed_off_by',
        'sign_off_notes',
        'created_by',
        'author_id',
    ];

    protected $casts = [
        'signed_off_at' => 'datetime',
    ];

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

    public function sections(): HasMany
    {
        return $this->hasMany(SpecDocumentSection::class)->orderBy('sort_order');
    }

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

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

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

    public function isSignedOff(): bool
    {
        return $this->signed_off_at !== null;
    }
}
