<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class FormTranslation extends Model
{
    use HasFactory, SoftDeletes;

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

    protected $fillable = [
        'form_id',
        'language',
        'name',
        'description',
        'fields',
        'pages',
        'form_setting',
        'status',
        'translated',
        'version',
        'adopted_from_global',
        'source_global_translation_id',
        'source_global_version',
        'last_local_edit_at',
    ];

    protected $casts = [
        'fields' => 'array',
        'pages' => 'array',
        'form_setting' => 'array',
        'translated' => 'boolean',
        'adopted_from_global' => 'boolean',
        'version' => 'integer',
        'source_global_version' => 'integer',
        'last_local_edit_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $model): void {
            if (empty($model->{$model->getKeyName()})) {
                $model->{$model->getKeyName()} = (string) Str::uuid();
            }

            $model->language = strtolower((string) ($model->language ?: 'en'));
        });
    }

    public function form(): BelongsTo
    {
        return $this->belongsTo(Form::class, 'form_id');
    }
    public function sourceGlobalTranslation(): BelongsTo
    {
        return $this->belongsTo(self::class, 'source_global_translation_id');
    }

    public function scopeByLanguage(Builder $query, string $language): Builder
    {
        return $query->where('language', strtolower(trim($language)));
    }
}
