<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('department_user', function (Blueprint $table) {
            $table->id();
            $table->foreignId('department_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('role_in_team')->nullable();
            $table->boolean('is_primary')->default(false);
            $table->timestamp('joined_at')->nullable();
            $table->timestamps();
            $table->unique(['department_id', 'user_id']);
        });

        DB::table('users')
            ->whereNotNull('department_id')
            ->orderBy('id')
            ->select(['id', 'department_id', 'job_title', 'created_at', 'updated_at'])
            ->chunk(100, function ($users) {
                foreach ($users as $user) {
                    DB::table('department_user')->updateOrInsert(
                        ['department_id' => $user->department_id, 'user_id' => $user->id],
                        [
                            'role_in_team' => $user->job_title,
                            'is_primary' => true,
                            'joined_at' => $user->created_at,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]
                    );
                }
            });
    }

    public function down(): void
    {
        Schema::dropIfExists('department_user');
    }
};
