<?php

namespace Database\Seeders;

use App\Models\Activity;
use App\Models\User;
use App\Models\Vote;
use App\Models\VoteItem;
use Illuminate\Database\Seeder;

class VoteSeeder extends Seeder
{
    public function run(): void
    {
        $ketua   = User::role('ketua')->first();
        $members = User::whereHas('roles')->get();

        $votes = [
            [
                'title'       => 'Persetujuan Program Kerja 2026',
                'description' => 'Voting untuk menyetujui program kerja organisasi tahun 2026',
                'type'        => 'general',
                'status'      => 'open',
                'deadline'    => now()->addDays(7),
                'created_by'  => $ketua?->id,
            ],
            [
                'title'       => 'Pengadaan Peralatan Olahraga',
                'description' => 'Pembelian peralatan olahraga senilai Rp 2.500.000',
                'type'        => 'finance',
                'status'      => 'closed',
                'deadline'    => now()->subDays(3),
                'created_by'  => $ketua?->id,
            ],
            [
                'title'       => 'Kegiatan Bakti Sosial Ramadan',
                'description' => 'Persetujuan kegiatan bakti sosial pembagian sembako',
                'type'        => 'activity',
                'status'      => 'open',
                'deadline'    => now()->addDays(2),
                'created_by'  => $ketua?->id,
            ],
        ];

        foreach ($votes as $data) {
            $vote = Vote::create($data);

            // Isi suara untuk voting yang sudah closed
            if ($vote->status === 'closed') {
                foreach ($members as $member) {
                    VoteItem::create([
                        'vote_id' => $vote->id,
                        'user_id' => $member->id,
                        'choice'  => collect(['approve', 'approve', 'approve', 'reject', 'abstain'])->random(),
                    ]);
                }
            }

            // Isi sebagian suara untuk voting yang masih open
            if ($vote->status === 'open') {
                foreach ($members->take(3) as $member) {
                    VoteItem::create([
                        'vote_id' => $vote->id,
                        'user_id' => $member->id,
                        'choice'  => collect(['approve', 'approve', 'reject'])->random(),
                    ]);
                }
            }
        }
    }
}
