<?php

namespace Database\Seeders;

use App\Models\ClinicalPathway;
use App\Models\PathwayTemplate;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use RuntimeException;

/**
 * Loads platform pathway packs from database/data/pathways/*.json.
 * Bindings store template_code only (resolve is_current at assessment start).
 */
class ClinicalPathwaySeeder extends Seeder
{
    public function run(): void
    {
        $dir = database_path('data/pathways');
        if (! is_dir($dir)) {
            $this->command?->warn("No pathway packs directory at {$dir}");

            return;
        }

        $files = collect(File::files($dir))
            ->filter(fn ($file) => str_ends_with(strtolower($file->getFilename()), '.json'))
            ->sortBy(fn ($file) => $file->getFilename())
            ->values();

        foreach ($files as $file) {
            $this->seedPack($file->getPathname());
        }
    }

    public function seedPack(string $path): ClinicalPathway
    {
        $data = json_decode(File::get($path), true);
        if (! is_array($data) || ! isset($data['pathway'])) {
            throw new RuntimeException("Invalid pathway pack: {$path}");
        }

        $p = $data['pathway'];
        if (empty($p['code']) || empty($p['name'])) {
            throw new RuntimeException("Pathway pack missing code/name: {$path}");
        }

        return DB::transaction(function () use ($p, $data, $path) {
            $pathway = ClinicalPathway::withTrashed()->where('code', $p['code'])->first();

            $attributes = [
                'code' => $p['code'],
                'name' => $p['name'],
                'description' => $p['description'] ?? null,
                'match_rules' => $p['match_rules'] ?? null,
                'is_active' => (bool) ($p['is_active'] ?? true),
                'sort_order' => (int) ($p['sort_order'] ?? 0),
                'meta' => $p['meta'] ?? null,
            ];

            if ($pathway) {
                if ($pathway->trashed()) {
                    $pathway->restore();
                }
                $pathway->fill($attributes)->save();
            } else {
                $pathway = ClinicalPathway::create($attributes);
            }

            PathwayTemplate::query()->where('pathway_id', $pathway->id)->delete();

            foreach ($data['templates'] ?? [] as $i => $binding) {
                if (empty($binding['template_code'])) {
                    throw new RuntimeException("Pathway pack binding missing template_code: {$path}");
                }
                PathwayTemplate::create([
                    'pathway_id' => $pathway->id,
                    'template_code' => $binding['template_code'],
                    'is_required_on_activation' => (bool) ($binding['is_required_on_activation'] ?? false),
                    'phase' => $binding['phase'] ?? PathwayTemplate::PHASE_ANY,
                    'sort_order' => (int) ($binding['sort_order'] ?? ($i + 1)),
                ]);
            }

            $this->command?->info(sprintf(
                'Seeded pathway %s (%d template bindings)',
                $pathway->code,
                count($data['templates'] ?? []),
            ));

            return $pathway->fresh('templates');
        });
    }
}
