<?php

namespace App\Components\Help\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\SoftDeleteResolution;

class HelpContent extends Model
{
    use SoftDeletes, SoftDeleteResolution;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'config.help_content';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'context_key',
        'title',
        'content',
        'version',
        'is_active'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
        'version' => 'integer',
    ];

    /**
     * Define which fields should be considered unique for conflict detection
     * This is used by the SoftDeleteResolution trait to detect conflicts
     */
    protected function uniqueFields(): array
    {
        return ['context_key', 'version'];
    }

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        // Before saving, check for conflicting soft-deleted records
        static::saving(function ($model) {
            try {
                $duplicate = $model->findSoftDeletedDuplicate();

                if ($duplicate) {
                    // If we find a soft-deleted duplicate, restore it with the new attributes
                    $model->restoreSoftDeletedRecord($duplicate, $model->getAttributes());
                    return false; // Prevent original save
                }
            } catch (\Exception $e) {
                \Log::error('Error checking for soft-deleted help content', [
                    'error' => $e->getMessage(),
                    'model' => get_class($model),
                    'attributes' => $model->getAttributes()
                ]);
            }

            return true;
        });
    }

    /**
     * Get the latest active version of help content for a given context key
     *
     * @param string $contextKey
     * @return HelpContent|null
     */
    public static function getLatestForContext(string $contextKey): ?HelpContent
    {
        return static::where('context_key', $contextKey)
            ->where('is_active', true)
            ->orderBy('version', 'desc')
            ->first();
    }

    /**
     * Create a new version of help content
     *
     * @param string $contextKey
     * @param string $title
     * @param string $content
     * @return HelpContent
     */
    public static function createNewVersion(string $contextKey, string $title, string $content): HelpContent
    {
        // Find the latest version
        $latestVersion = static::where('context_key', $contextKey)
            ->orderBy('version', 'desc')
            ->value('version') ?? 0;

        // Create new version
        return static::create([
            'context_key' => $contextKey,
            'title' => $title,
            'content' => $content,
            'version' => $latestVersion + 1,
            'is_active' => true
        ]);
    }

    /**
     * Set this help content as the active version for its context
     *
     * @return bool
     */
    public function setAsActive(): bool
    {
        // Deactivate all other versions for this context
        static::where('context_key', $this->context_key)
            ->where('id', '!=', $this->id)
            ->update(['is_active' => false]);

        // Set this version as active
        $this->is_active = true;
        return $this->save();
    }
}
