<?php

namespace App\Domain\Inventory\Models;

use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Shared\Traits\ManglesUniqueOnDelete;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Domain\Shared\Traits\BelongsToBranch;

class Kit extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable, ManglesUniqueOnDelete, BelongsToBranch;

    protected array $uniqueFieldsToMangle = ['sku'];

    protected $fillable = [
        'academy_id', 'branch_id',
        'name_ar',
        'name',
        'sku',
        'description_ar',
        'selling_price',
        'is_active',
        'assembly_instructions',
        'photo_path',
        'created_by',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'selling_price' => 'integer',
            'is_active' => 'boolean',
            'metadata' => 'array',
        ];
    }

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

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

    /**
     * Programmes that require this kit. The inverse of
     * TrainingProgram::bundledKits().
     */
    public function programs()
    {
        return $this->belongsToMany(
            \App\Domain\Training\Models\TrainingProgram::class,
            'program_kits',
            'kit_id',
            'training_program_id'
        )->withPivot(['is_required', 'quantity'])->withTimestamps();
    }
}
