﻿<?php

namespace App\Models;

use App\Scopes\OrganisationScope;
use Spatie\Activitylog\LogOptions;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class RatingType extends Model
{
    use HasFactory;

    protected $table = 'rating_types';

    protected $fillable = [
        'organisation_id',
        'name',
        'type',
        'config',
        'is_required',
        'is_weighted',
        'is_default',
        'is_visible_to_employee',
    ];

    use LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->useLogName('Rating Type')
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn(string $eventName) => " {$this->name} Rating type has been {$eventName}")
            ->dontSubmitEmptyLogs();
    }

    protected $casts = [
        'config' => 'array',
        'is_required' => 'boolean',
        'is_weighted' => 'boolean',
        'is_default' => 'boolean',
        'is_visible_to_employee' => 'boolean',
    ];

    /**
     * Relationship with Organisation (if applicable)
     */
    public function organisation()
    {
        return $this->belongsTo(Organisation::class);
    }

    /**
     * Accessor: Get config option by key
     */
    public function getConfigOption($key, $default = null)
    {
        return $this->config[$key] ?? $default;
    }

    /**
     * Helper: Check if this is a numeric type
     */
    public function isNumeric()
    {
        return $this->type === 'numeric' || $this->type === 'percentage';
    }

    /**
     * Helper: Get allowed values (if defined)
     */
    public function getAllowedValues()
    {
        return $this->config['options'] ?? null;
    }

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

    protected static function booted()
    {
        static::addGlobalScope(new OrganisationScope);

        static::creating(function ($model) {
            if (Auth::check()) {
                $model->organisation_id = Auth::user()->organisation_id;
            }
        });
    }