<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // ----------------------
        // Languages Table
        // ----------------------
        Schema::create('languages', function (Blueprint $table) {
            $table->id();
            $table->string('name');        // e.g., English
            $table->string('code', 5)->unique(); // e.g., en, fr, es
            $table->string('locale', 10)->nullable(); // e.g., en_US, fr_FR
            $table->boolean('is_active')->default(true);
            $table->timestampsTz();
            $table->softDeletesTz();
        });

        // ----------------------
        // Company Languages (default language for company)
        // ----------------------
        Schema::create('company_languages', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('company_id'); // optional FK if companies table exists
            $table->foreignId('language_id')->constrained('languages')->cascadeOnDelete();
            $table->boolean('is_default')->default(false); // default language for company
            $table->timestampsTz();
            $table->unique(['company_id', 'language_id']);
        });

        // ----------------------
        // User Languages (preferred language)
        // ----------------------
        Schema::create('user_languages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('language_id')->constrained('languages')->cascadeOnDelete();
            $table->timestampsTz();
            $table->unique(['user_id', 'language_id']);
        });

        // ----------------------
        // Optional: Translations Table
        // ----------------------
        Schema::create('translations', function (Blueprint $table) {
            $table->id();
            $table->string('key'); // translation key, e.g., 'welcome_message'
            $table->foreignId('language_id')->constrained('languages')->cascadeOnDelete();
            $table->text('value'); // translated text
            $table->timestampsTz();
            $table->unique(['key', 'language_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('translations');
        Schema::dropIfExists('user_languages');
        Schema::dropIfExists('company_languages');
        Schema::dropIfExists('languages');
    }
};
