<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class WarehouseSeeder extends Seeder
{
    public function run(): void
    {
        $warehouses = [
            [
                'code'       => 'GDG-01',
                'name'       => 'Gudang Utama',
                'address'    => 'Jl. Raya Utama No. 1, Jakarta Pusat',
                'phone'      => '021-5550001',
                'is_active'  => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'code'       => 'GDG-02',
                'name'       => 'Gudang Cabang',
                'address'    => 'Jl. Cabang No. 15, Bandung',
                'phone'      => '022-5550002',
                'is_active'  => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
            [
                'code'       => 'GDG-03',
                'name'       => 'Gudang Online',
                'address'    => 'Jl. E-Commerce Park Blok A5, Tangerang',
                'phone'      => '021-5550003',
                'is_active'  => true,
                'created_at' => now(),
                'updated_at' => now(),
            ],
        ];

        foreach ($warehouses as $wh) {
            DB::table('warehouses')->updateOrInsert(
                ['code' => $wh['code']],
                $wh
            );
        }

        // Ensure all active products have warehouse_stock entries for every active warehouse
        $warehouseIds = DB::table('warehouses')->where('is_active', true)->pluck('id');
        $products     = DB::table('products')->whereNull('deleted_at')->get(['id', 'current_stock', 'min_stock']);

        foreach ($warehouseIds as $whId) {
            foreach ($products as $product) {
                $exists = DB::table('warehouse_stock')
                    ->where('warehouse_id', $whId)
                    ->where('product_id', $product->id)
                    ->exists();

                if (!$exists) {
                    DB::table('warehouse_stock')->insert([
                        'warehouse_id'  => $whId,
                        'product_id'    => $product->id,
                        'current_stock' => 0, // New warehouses start at 0
                        'min_stock'     => $product->min_stock,
                        'created_at'    => now(),
                        'updated_at'    => now(),
                    ]);
                }
            }
        }
    }
}
