<?php

namespace App\Traits;

use App\Models\Seed;
use App\Master\Models\Seed as GlobalSeed;
use Illuminate\Support\Facades\Log;

trait TrackedSeeding
{
    private function trackedSeed(string $seeder, bool $force = false, bool $global = false): void
    {
        $model = $global ? GlobalSeed::class : Seed::class;

        if ($this->alreadySeeded($seeder, $model) && !$force) {
            return;
        }
        if (method_exists($this, 'info')) {
            $this->info("Seeding $seeder");
        }

        try {
            (new $seeder())->run();
            $model::query()
                ->updateOrCreate([
                    'seeder' => $seeder,
                    'batch' => $this->batch
                ]);
        } catch (\Exception $exception) {
            Log::error("Failed to seed $seeder", [
                'tenant' => tenant('id'),
                'exception' => $exception->getMessage(),
            ]);
        }
    }

    private function alreadySeeded(string $seeder, $model): bool
    {
        return $model::query()->where('seeder', $seeder)->exists();
    }
}
