<?php

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

/**
 * Unit-of-measure nomenclator.
 *  - Adds `units` table (per-tenant, 3 language names).
 *  - Adds nullable `unit_id` FK on parts, wo_parts, purchase_items, labor_parts.
 *  - Seeds ~10 standard units for every existing tenant.
 *  - Backfills unit_id on each row by matching the free-text `unit` column.
 *  - Keeps the old string `unit` column as fallback (display logic prefers unit_id).
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('units')) {
            Schema::create('units', function (Blueprint $t) {
                $t->id();
                $t->foreignId('company_id')->constrained('companies')->cascadeOnDelete();
                $t->string('code', 16);
                $t->string('name_ro', 40);
                $t->string('name_ru', 40);
                $t->string('name_en', 40);
                $t->boolean('is_active')->default(true);
                $t->integer('sort_order')->default(0);
                $t->timestamps();
                $t->unique(['company_id', 'code']);
            });
        }

        foreach (['parts', 'wo_parts', 'purchase_items', 'labor_parts'] as $table) {
            if (! Schema::hasColumn($table, 'unit_id')) {
                Schema::table($table, function (Blueprint $t) {
                    $t->foreignId('unit_id')->nullable()->after('unit')->constrained('units')->nullOnDelete();
                });
            }
        }

        $defaults = [
            ['code' => 'buc',  'ro' => 'buc',  'ru' => 'шт',    'en' => 'pcs',     'sort' => 10],
            ['code' => 'set',  'ro' => 'set',  'ru' => 'компл', 'en' => 'set',     'sort' => 20],
            ['code' => 'l',    'ro' => 'l',    'ru' => 'л',     'en' => 'L',       'sort' => 30],
            ['code' => 'ml',   'ro' => 'ml',   'ru' => 'мл',    'en' => 'mL',      'sort' => 40],
            ['code' => 'kg',   'ro' => 'kg',   'ru' => 'кг',    'en' => 'kg',      'sort' => 50],
            ['code' => 'g',    'ro' => 'g',    'ru' => 'г',     'en' => 'g',       'sort' => 60],
            ['code' => 'm',    'ro' => 'm',    'ru' => 'м',     'en' => 'm',       'sort' => 70],
            ['code' => 'cm',   'ro' => 'cm',   'ru' => 'см',    'en' => 'cm',      'sort' => 80],
            ['code' => 'm2',   'ro' => 'm²',   'ru' => 'м²',    'en' => 'sq.m',    'sort' => 90],
            ['code' => 'ora',  'ro' => 'oră',  'ru' => 'час',   'en' => 'hour',    'sort' => 100],
            ['code' => 'pack', 'ro' => 'pach', 'ru' => 'уп',    'en' => 'pack',    'sort' => 110],
        ];

        $companies = DB::table('companies')->pluck('id');
        $now = now();
        foreach ($companies as $companyId) {
            foreach ($defaults as $u) {
                DB::table('units')->insertOrIgnore([
                    'company_id' => $companyId,
                    'code' => $u['code'],
                    'name_ro' => $u['ro'],
                    'name_ru' => $u['ru'],
                    'name_en' => $u['en'],
                    'is_active' => true,
                    'sort_order' => $u['sort'],
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }

            $extraCodes = collect();
            foreach (['parts', 'wo_parts', 'purchase_items', 'labor_parts'] as $table) {
                $codes = DB::table($table)
                    ->where('company_id', $companyId)
                    ->whereNotNull('unit')
                    ->distinct()->pluck('unit')->filter()->map(fn ($c) => trim((string) $c))->filter();
                $extraCodes = $extraCodes->merge($codes);
            }
            $extraCodes = $extraCodes->unique();

            // Case-insensitive dedupe: MariaDB default collation treats 'L' == 'l'
            // as the same value on the unique index, so we compare lowercased.
            $existingCodes = DB::table('units')->where('company_id', $companyId)
                ->pluck('code')->map(fn ($c) => mb_strtolower((string) $c))->all();
            foreach ($extraCodes as $code) {
                if (in_array(mb_strtolower($code), $existingCodes, true)) continue;
                if (mb_strlen($code) > 16) continue;
                DB::table('units')->insertOrIgnore([
                    'company_id' => $companyId,
                    'code' => $code,
                    'name_ro' => $code,
                    'name_ru' => $code,
                    'name_en' => $code,
                    'is_active' => true,
                    'sort_order' => 200,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }

            foreach (['parts', 'wo_parts', 'purchase_items', 'labor_parts'] as $table) {
                DB::statement("
                    UPDATE {$table}
                    SET unit_id = (
                        SELECT id FROM units
                        WHERE units.company_id = {$table}.company_id
                          AND units.code = {$table}.unit
                        LIMIT 1
                    )
                    WHERE {$table}.company_id = ?
                      AND {$table}.unit_id IS NULL
                      AND {$table}.unit IS NOT NULL
                ", [$companyId]);
            }
        }
    }

    public function down(): void
    {
        foreach (['parts', 'wo_parts', 'purchase_items', 'labor_parts'] as $table) {
            Schema::table($table, function (Blueprint $t) {
                $t->dropForeign(['unit_id']);
                $t->dropColumn('unit_id');
            });
        }
        Schema::dropIfExists('units');
    }
};
