<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * Migrate tipe_dokumen from m_raw_materials to m_store_raw_materials
     * This is needed because tipe_dokumen should be per store-item mapping,
     * not per item globally.
     *
     * @return void
     */
    public function up()
    {
        // Copy tipe_dokumen from m_raw_materials to all existing m_store_raw_materials mappings
        DB::statement("
            UPDATE m_store_raw_materials srm
            SET tipe_dokumen = COALESCE(rm.tipe_dokumen, 'DO')
            FROM m_raw_materials rm
            WHERE srm.raw_material_id = rm.id
            AND srm.delete_flag = 0
        ");
        
        // Log the migration
        \Log::info('Migrated tipe_dokumen from m_raw_materials to m_store_raw_materials');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Cannot reverse this migration as we don't know which tipe_dokumen was original
        \Log::warning('Cannot reverse tipe_dokumen migration - data already migrated');
    }
};
