<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('backend_user_id')->nullable();
            $table->string('code', 15)->unique();
            $table->nullableTimestamps();

            $table->foreign('backend_user_id')->references('id')
                ->on('backend_users')->onDelete('SET NULL')->onUpdate('CASCADE');
        });

        Schema::create('department_languages', function (Blueprint $table) {
            $table->bigIncrements('translation_id');
            $table->unsignedBigInteger('department_id');
            $table->string('language_id', 10);

            $table->string('title', 150);

            // Languages
            $table->unique(['department_id', 'language_id'], 'idx_department_language');
            $table->foreign('department_id')
                ->references('id')
                ->on('departments')
                ->onDelete('CASCADE')
                ->onUpdate('CASCADE');
        });

        Schema::create('department_cpvs', function (Blueprint $table) {
            $table->unsignedBigInteger('department_id');
            $table->unsignedBigInteger('cpv_id');
            $table->integer('position')->nullable();
            $table->primary(['department_id', 'cpv_id']);

            $table->foreign('department_id')->references('id')
                ->on('departments')->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('cpv_id')->references('id')
                ->on('cpvs')->onDelete('CASCADE')->onUpdate('CASCADE');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('department_cpvs');
        Schema::dropIfExists('department_languages');
        Schema::dropIfExists('departments');
    }
};
