<?php

namespace App\Models;

use App\Models\ValidationModel;
use App\Models\User;
use App\Models\Status;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class StatusChange extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'status_changes';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['related_id', 'related_type', 'old_status', 'new_status', 'changed_by'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'related_id'   => 'required',
        'related_type' => 'required',
        'old_status'   => 'required',
        'new_status'   => 'required',
    ];

    /**
     * Insert the validation checks on the model.
     * The model only gets created if the validation checks pass.
     *
     * @var void
     */
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->changed_by = getAuthUserId();
        });
    }

    /**
     * Returns all the statuses for tasks.
     */
    public function scopeTasks($query)
    {
        return $query->where('related_type', 'task');
    }

    /**
     * Retrieve the old status data.
     *
     * @return \Status
     */
    public function old_status()
    {
        return $this->belongsTo(Status::class, 'old_status');
    }

    /**
     * Retrieve the new status data.
     *
     * @return \Status
     */
    public function new_status()
    {
        return $this->belongsTo(Status::class, 'new_status');
    }

    /**
     * Retrieves the user who changed the status.
     *
     * @return \User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'changed_by');
    }

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