<?php

use App\Modules\HR\EmploymentStatuses\Repositories\EmploymentStatusRepository;
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
    {
        if (! Schema::hasColumn('employees', 'employment_status')) {
            return;
        }

        $defaults = config('hr_employment_statuses.defaults', []);
        $statuses = app(EmploymentStatusRepository::class);

        DB::table('tenants')->orderBy('id')->pluck('id')->each(function ($tenantId) use ($defaults, $statuses): void {
            $statuses->seedDefaults((int) $tenantId, $defaults);
        });

        DB::table('employees')
            ->select(['id', 'tenant_id', 'employment_status'])
            ->orderBy('id')
            ->chunkById(200, function ($rows) use ($statuses): void {
                foreach ($rows as $row) {
                    $code = (string) ($row->employment_status ?: 'full_time');
                    $statusId = $statuses->findIdByLegacyCode((int) $row->tenant_id, $code)
                        ?? $statuses->findIdByLegacyCode((int) $row->tenant_id, 'full_time');

                    if ($statusId !== null) {
                        DB::table('employees')
                            ->where('id', $row->id)
                            ->update(['employment_status_id' => $statusId]);
                    }
                }
            });

        Schema::table('employees', function (Blueprint $table): void {
            $table->dropColumn('employment_status');
        });
    }

    public function down(): void
    {
        if (Schema::hasColumn('employees', 'employment_status')) {
            return;
        }

        Schema::table('employees', function (Blueprint $table): void {
            $table->string('employment_status', 40)->default('full_time')->after('national_id');
        });

        DB::table('employees')
            ->join('employment_statuses', 'employment_statuses.id', '=', 'employees.employment_status_id')
            ->whereNotNull('employees.employment_status_id')
            ->update([
                'employees.employment_status' => DB::raw('employment_statuses.code'),
            ]);
    }
};
