<?php

namespace Database\Seeders;

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

class ActiveSubstancesTableSeeder extends Seeder
{
    /**
     * Seed the active substances catalogue and pivot data.
     */
    public function run(): void
    {
        echo 'Seeding active substances...' . PHP_EOL;

        DB::table('item_active_substance')->delete();
        DB::table('active_substances')->delete();

        $catalogue = [
            'Vitamin A' => [3, 21],
            'Vitamin C' => [3, 22],
            'Zinc' => [3, 5, 24],
            'L-Arginine' => [5],
            'Panax Ginseng' => [5],
            'Acetylsalicylic Acid' => [18],
            'Paracetamol' => [21],
            'Ibuprofen' => [22],
            'Cetirizine Hydrochloride' => [24],
            'Hydrocortisone' => [25],
        ];

        $pharmacyLookup = DB::table('items')
            ->where('product_type', 'pharmacy')
            ->pluck('id')
            ->flip();

        $timestamp = Carbon::now();

        $substances = [];
        foreach ($catalogue as $name => $itemIds) {
            $validItems = array_values(array_filter(array_unique($itemIds), static function ($itemId) use ($pharmacyLookup) {
                return $pharmacyLookup->has($itemId);
            }));

            if (empty($validItems)) {
                continue;
            }

            $substances[$name] = [
                'name' => $name,
                'created_at' => $timestamp,
                'updated_at' => $timestamp,
            ];

            $catalogue[$name] = $validItems;
        }

        if (empty($substances)) {
            return;
        }

        DB::table('active_substances')->insert(array_values($substances));

        $substanceIds = DB::table('active_substances')
            ->whereIn('name', array_keys($substances))
            ->pluck('id', 'name');

        $pivotRows = [];
        foreach ($catalogue as $name => $itemIds) {
            $substanceId = $substanceIds[$name] ?? null;

            if (! $substanceId) {
                continue;
            }

            foreach ($itemIds as $itemId) {
                $pivotRows[] = [
                    'item_id' => $itemId,
                    'active_substance_id' => $substanceId,
                    'created_at' => $timestamp,
                    'updated_at' => $timestamp,
                ];
            }
        }

        if (! empty($pivotRows)) {
            DB::table('item_active_substance')->insert($pivotRows);
        }
    }
}
