<?php

namespace Database\Factories;

use App\Models\Unit;
use Illuminate\Database\Eloquent\Factories\Factory;

class UnitFactory extends Factory
{
    protected $model = Unit::class;

    public function definition()
    {
        $units = [
            ['name' => 'Piece', 'abbreviation' => 'pcs', 'is_base_unit' => true],
            ['name' => 'Kilogram', 'abbreviation' => 'kg', 'is_base_unit' => true],
            ['name' => 'Gram', 'abbreviation' => 'g', 'is_base_unit' => false],
            ['name' => 'Liter', 'abbreviation' => 'L', 'is_base_unit' => true],
            ['name' => 'Milliliter', 'abbreviation' => 'mL', 'is_base_unit' => false],
            ['name' => 'Meter', 'abbreviation' => 'm', 'is_base_unit' => true],
            ['name' => 'Centimeter', 'abbreviation' => 'cm', 'is_base_unit' => false],
            ['name' => 'Dozen', 'abbreviation' => 'dz', 'is_base_unit' => false],
            ['name' => 'Box', 'abbreviation' => 'box', 'is_base_unit' => false],
            ['name' => 'Pack', 'abbreviation' => 'pack', 'is_base_unit' => false],
        ];

        $unit = $this->faker->randomElement($units);
        
        $data = [
            'name' => $unit['name'],
            'abbreviation' => $unit['abbreviation'],
            'description' => $this->faker->sentence(),
            'status' => $this->faker->randomElement(['active', 'inactive']),
            'is_base_unit' => $unit['is_base_unit'],
            'conversion_rate' => $unit['is_base_unit'] ? 1 : $this->faker->randomFloat(4, 0.001, 1000),
        ];
        
        if (!$unit['is_base_unit']) {
            // Assign a random base unit
            $data['base_unit_id'] = Unit::where('is_base_unit', true)->inRandomOrder()->first()->id ?? null;
        }
        
        return $data;
    }
}