﻿<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class JobDescriptionVersion extends Model
{
    use HasFactory;

    const UPDATED_AT = null;

    protected $fillable = [
        'job_description_id',
        'version_number',
        'snapshot_json',
        'created_by',
    ];

    protected $casts = [
        'snapshot_json'  => 'array',
        'version_number' => 'integer',
        'created_at'     => 'datetime',
    ];

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

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

    public function scopeLatest($query)
    {
        return $query->orderByDesc('version_number');
    }

    /**
     * Retrieve a specific section's content from the snapshot.
     */
    public function getSectionContent(string $sectionType): ?string
    {
        $sections = collect($this->snapshot_json['sections'] ?? []);

        return $sections->firstWhere('section_type', $sectionType)['content'] ?? null;
    