<?php

namespace Database\Seeders;

use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory;
class DependentSeeder extends Seeder
{
    public function run(): void
    {
        DB::disableQueryLog();
        Model::unsetEventDispatcher();

        $chunkSize = 100;
        $tableName = 'dependents';
        $now = CarbonImmutable::now();
        $startDate = $now->subMonths(12);

        $memberIds = DB::table('members')->pluck('id')->toArray();
        if (empty($memberIds)) {
            $this->command->warn('No members found. Run MemberSeeder first.');
            return;
        }

        $faker = Factory::create();
        $relations = [1, 2, 3, 4];

        $total = 0;
        $rows = [];

        foreach ($memberIds as $memberId) {
            $dependentsCount = rand(3, 5);

            for ($j = 0; $j < $dependentsCount; $j++) {
                $relation = $relations[array_rand($relations)];

                $isChild = in_array($relation, [2, 3], true);
                $firstName = $faker->firstName;
                $lastName = $faker->lastName;

                $name = 'd' . '-' . $firstName . ' ' . $lastName;

                $createdAt = CarbonImmutable::createFromTimestamp(
                    rand($startDate->timestamp, $now->timestamp)
                )->setTime(12, 0, 0)->format('Y-m-d H:i:s');
                $createdAtCarbon = CarbonImmutable::parse($createdAt);
                $dob = $isChild
                    ? $createdAtCarbon->subYears(rand(5, 17))->format('Y-m-d')
                    : $createdAtCarbon->subYears(rand(25, 60))->format('Y-m-d');

                $total++;
                $rows[] = [
                    'name'               => $name,
                    'relation'           => $relation,
                    'dob'                => $dob,
                    'phone'              => rand(0, 3) ? '05' . str_pad(20000000 + $total, 8, '0', STR_PAD_LEFT) : null,
                    'status'             => [1, 2, 2][array_rand([1, 2, 2])],
                    'assigned_member_id' => $memberId,
                    'created_at'         => $createdAt,
                    'updated_at'         => $createdAt,
                ];

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

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

        $this->command->info("Dependents seeded: {$total} records");
    }
}
