<?php

namespace Daylight\Core\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Carbon;

class PublishModelsCommand extends Command
{
    protected $signature = 'daylight:publish-models';

    protected $description = 'Genereer lege models die extenden van Daylight Core models';

    public function handle()
    {
        $files = new Filesystem;

        $stub = $files->get(__DIR__.'/../../stubs/DummyModel.stub');
        $packageModelRoot = realpath(__DIR__.'/../../src/Models');
        $publishRoot = app_path('Models');

        foreach ($files->allFiles($packageModelRoot) as $file) {
            if ($file->getExtension() !== 'php') {
                continue;
            }

            // Bepaal het pad relatief aan de model-root (niet de volledige package-root)
            $absolutePath = $file->getRealPath();
            $relativePath = str_replace($packageModelRoot.DIRECTORY_SEPARATOR, '', $absolutePath);
            $relativeDir = dirname($relativePath);
            $className = $file->getBasename('.php');

            // Volledige use class op basis van relatieve locatie
            $baseNamespace = 'Daylight\\Core\\Models';
            $subNamespace = str_replace('/', '\\', $relativeDir !== '.' ? $relativeDir : '');
            $fullBaseClass = $baseNamespace.($subNamespace ? '\\'.$subNamespace : '').'\\'.$className;

            // Volledige namespace voor de nieuwe model
            $targetNamespace = rtrim('App\\Models\\'.($subNamespace ? '\\'.$subNamespace : ''), '\\');

            // Maak outputmap aan
            $destinationDir = $publishRoot.($relativeDir !== '.' ? '/'.$relativeDir : '');
            $destinationFile = $destinationDir.'/'.$className.'.php';

            if (! $files->isDirectory($destinationDir)) {
                $files->makeDirectory($destinationDir, 0755, true);
            }

            if ($files->exists($destinationFile)) {
                $this->warn("Bestaat al: {$relativePath} — overgeslagen");

                continue;
            }

            $output = str_replace(
                ['DummyNamespace', 'DummyClass', 'DummyFullBaseClass', 'DummyShortBaseClass', 'DummyTimestamp'],
                [$targetNamespace, $className, $fullBaseClass, $className, Carbon::now()],
                $stub
            );

            $files->put($destinationFile, $output);
            $this->info("Gegenereerd: {$relativePath}");
        }

        $this->info('Alle models succesvol gegenereerd.');
    }
}
