<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Loan;
use App\Models\User;
use App\Models\Book;
use App\Services\DummyDataService;
use Carbon\Carbon;

class LoanSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $books = DummyDataService::getAllBooks();

        foreach ($books as $data) {
            if ($data['user_id'] && $data['status'] !== 'Tersedia') {
                // In dummy data, user_id is sometimes an array, handle it
                $userIds = is_array($data['user_id']) ? $data['user_id'] : [$data['user_id']];
                
                foreach ($userIds as $uId) {
                    $user = User::find($uId);
                    $book = Book::find($data['id']);

                    if ($user && $book) {
                        Loan::updateOrCreate(
                            [
                                'user_id' => $user->id,
                                'book_id' => $book->id,
                                'status' => $data['status'],
                            ],
                            [
                                'loan_code' => 'PIN-' . date('Ym') . '-' . sprintf('%03d', $book->id),
                                'borrowed_at' => Carbon::now()->subDays(7),
                                'due_at' => Carbon::now()->addDays($data['sisa_hari'] ?? 7),
                                'status' => $data['status'],
                            ]
                        );
                    }
                }
            }
        }
    }
}
