<?php

namespace App\Models;

use App\Traits\Auditable;
use App\Traits\DeleteGuarded;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Department extends Model
{
    use HasFactory, SoftDeletes, Auditable, DeleteGuarded;

    protected $fillable = ['name', 'description', 'email', 'creator_by', 'last_updated_by', 'deleted_by'];
    public const DELETE_PREVENTING_RELATIONSHIPS = [
        // [
        //     "name" => "positions",
        //     "message" => "This department has :count positions, therefore can't be deleted"
        // ]
    ];
    public const DELETE_AFFECTED_RELATIONSHIPS = [
        [
            "name" => "positions",
            "message" => "This department has :count positions, when deleted, these positions will no longer belong to departments",
            "action" => "detachPositions"
        ]
    ];
    public const NON_STANDALONE_CHILDREN = [];

    /**
     * Get the audit descriptions for different actions.
     *
     * @return array An array containing descriptions for different audit actions
     */
    protected function getAuditDescriptions(): array
    {
        return [
            'create' => "Created new department: $this->name",
            'update' => "Updated department details: $this->name",
            'delete' => "Deleted department: $this->name",
        ];
    }



    /**
     * Get the positions that belong under the department
     * @return HasMany
     */
    public function positions(): HasMany
    {
        return $this->HasMany(Position::class);
    }

    /**
     * Detach the positions associated with the department
     * @return void
     */
    protected function detachPositions(): void
    {
        $this->positions()->update(['department_id' => null]);
    }

    /**
     * Get the user who created the department
     * @return BelongsTo
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the who last-updated the department
     * @return BelongsTo
     */
    public function last_updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'last_updated_by');
    }
}
