<?php

namespace App\Models;

use App\Traits\Archivable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class WhatsappMessage extends Model
{
    use HasFactory, SoftDeletes, Archivable;

    protected $table = 'whatsapp_messages';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'franchisee_id',
        'is_global',
        'source_message_id',
        'order_no',
        'type',
        'question_type',
        'key',
        'header_text',
        'body_text',
        'footer_text',
        'options',
        'age_options',
        'program_map',
        'media_url',
        'program_id',
        'expects',
        'is_active',
        'created_by',
    ];

    protected $casts = [
        'options' => 'array',
        'age_options' => 'array',
        'program_map' => 'array',
        'is_active' => 'boolean',
        'is_global' => 'boolean',
        'order_no' => 'integer',
    ];

    public const TYPE_TEXT = 'text';
    public const TYPE_BUTTONS = 'buttons';
    public const TYPE_LIST = 'list';
    public const TYPE_VIDEO = 'video';
    public const TYPE_IMAGE = 'image';

    public const QUESTION_CUSTOM = 'custom';
    public const QUESTION_AGE = 'age';
    public const QUESTION_PROGRAM = 'program';

    public const EXPECTS_NONE = 'none';
    public const EXPECTS_TEXT = 'text';
    public const EXPECTS_NUMBER = 'number';
    public const EXPECTS_OPTION = 'option';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->id)) {
                $model->id = (string) Str::uuid();
            }
        });
    }

    public function translations()
    {
        return $this->hasMany(WhatsappMessageTranslation::class, 'whatsapp_message_id');
    }

    public function franchisee()
    {
        return $this->belongsTo(Franchisee::class, 'franchisee_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * The effective ordered flow for a franchisee: their own messages if they have
     * any, otherwise the global (admin) default flow.
     */
    public static function effectiveFlowFor(?string $franchiseeId)
    {
        if ($franchiseeId) {
            $own = static::query()
                ->where('franchisee_id', $franchiseeId)
                ->orderBy('order_no')
                ->get();

            if ($own->isNotEmpty()) {
                return $own;
            }
        }

        return static::query()
            ->where('is_global', true)
            ->orderBy('order_no')
            ->get();
    }
}
