<?php

namespace Database\Seeders;

use App\Enums\RawMaterialUnit;
use App\Models\RawMaterial;
use App\Models\RawMaterialPrice;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class RawMaterialSeeder extends Seeder
{
    public function run(): void
    {
        $rawMaterials = [
            [
                'name' => 'Kain Katun Premium',
                'unit' => RawMaterialUnit::METER,
                'prices' => [
                    ['variant' => 'Putih', 'price' => 35000, 'stock' => 120.5],
                    ['variant' => 'Merah Maroon', 'price' => 38000, 'stock' => 85.25],
                    ['variant' => 'Navy', 'price' => 38000, 'stock' => 64.0],
                ],
            ],
            [
                'name' => 'Kain Rayon Motif',
                'unit' => RawMaterialUnit::YARD,
                'prices' => [
                    ['variant' => 'Batik Parang', 'price' => 42000, 'stock' => 200.0],
                    ['variant' => 'Batik Kawung', 'price' => 45000, 'stock' => 175.5],
                    ['variant' => 'Polos Hitam', 'price' => 32000, 'stock' => 90.0],
                ],
            ],
            [
                'name' => 'Kain Knit',
                'unit' => RawMaterialUnit::METER,
                'prices' => [
                    ['variant' => 'Putih', 'price' => 85000, 'stock' => 12.5],
                    ['variant' => 'Merah', 'price' => 85000, 'stock' => 10.0],
                    ['variant' => 'Navy', 'price' => 90000, 'stock' => 8.25],
                ],
            ],
        ];

        try {
            DB::transaction(function () use ($rawMaterials): void {
                foreach ($rawMaterials as $rawMaterialData) {
                    $rawMaterial = RawMaterial::factory()->create([
                        'name' => $rawMaterialData['name'],
                        'unit' => $rawMaterialData['unit'],
                        'is_active' => true,
                    ]);

                    foreach ($rawMaterialData['prices'] as $priceData) {
                        RawMaterialPrice::factory()->create([
                            'raw_material_id' => $rawMaterial->id,
                            'variant' => $priceData['variant'],
                            'price' => $priceData['price'],
                            'stock' => $priceData['stock'],
                        ]);
                    }
                }
            });
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}
