<?php

namespace Database\Seeders;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class BookingParticipantSeeder extends Seeder
{
    public function run(): void
    {
        DB::disableQueryLog();
        Model::unsetEventDispatcher();

        $chunkSize = 100;
        $tableName = 'booking_participants';
        $now = CarbonImmutable::now();

        $bookings = DB::table('bookings')->get(['id', 'member_id']);
        if ($bookings->isEmpty()) {
            $this->command->warn('No bookings found. Run BookingSeeder first.');
            return;
        }

        $memberIds = DB::table('members')->pluck('id')->toArray();
        $dependentIdsByMember = DB::table('dependents')
            ->select('assigned_member_id', 'id')
            ->get()
            ->groupBy('assigned_member_id')
            ->map(fn ($g) => $g->pluck('id')->toArray())
            ->toArray();

        $rows = [];
        $totalInserted = 0;

        foreach ($bookings as $booking) {
            $createdAt = $now->copy()->subDays(rand(0, 30))->setTime(12, 0, 0)->format('Y-m-d H:i:s');

            $rows[] = [
                'booking_id'   => $booking->id,
                'member_id'    => $booking->member_id,
                'dependent_id' => null,
                'status'       => 2,
                'is_creator'   => true,
                'created_at'   => $createdAt,
                'updated_at'   => $createdAt,
            ];

            $dependents = $dependentIdsByMember[$booking->member_id] ?? [];
            if (!empty($dependents) && rand(0, 3) === 0) {
                $depId = $dependents[array_rand($dependents)];
                $rows[] = [
                    'booking_id'   => $booking->id,
                    'member_id'    => null,
                    'dependent_id' => $depId,
                    'status'       => 2,
                    'is_creator'   => false,
                    'created_at'   => $createdAt,
                    'updated_at'   => $createdAt,
                ];
            }

            if (count($rows) >= $chunkSize) {
                DB::table($tableName)->insert($rows);
                $totalInserted += count($rows);
                $rows = [];
            }
        }

        if (!empty($rows)) {
            DB::table($tableName)->insert($rows);
            $totalInserted += count($rows);
        }

        $this->command->info("BookingParticipants seeded: {$totalInserted} records");
    }
}
