<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Bag;
use App\Models\BagItem;
use App\Models\Parcel;
use App\Models\Rider;
use App\Models\Branch;

class BagAndItemsSeeder extends Seeder
{
    /**
     * Seed a test bag with a couple of parcels for manifest verification.
     */
    public function run(): void
    {
        $rider = Rider::first();

        $origin = Branch::first();
        $destination = Branch::skip(1)->first() ?? $origin;

        $bag = Bag::firstOrCreate(
            ['bag_number' => 'BAG777777'],
            [
                'status' => 'sealed',
                'rider_id' => $rider?->id,
                'origin_branch_id' => $origin?->id,
                'destination_branch_id' => $destination?->id,
            ]
        );

        $trackingIds = ['PCL162819', 'PCL162820'];
        foreach ($trackingIds as $tid) {
            $parcel = Parcel::where('tracking_id', $tid)->first();
            if ($parcel && !BagItem::where('bag_id', $bag->id)->where('parcel_id', $parcel->id)->exists()) {
                BagItem::create([
                    'bag_id' => $bag->id,
                    'parcel_id' => $parcel->id,
                ]);
            }
        }

        echo "Seeded bag id: {$bag->id}\n";
    }
}