<?php

namespace Lucent\Commands;

use Illuminate\Console\Command;
use Lucent\Primitive\Collection;
use Lucent\Schema\CollectionSchema;
use Lucent\Schema\Ui\Text;

class GenerateCollectionSchema extends Command
{

    protected $signature = 'lucent:make:collection-schema {name} {fields?}';

    protected $description = 'Generate a lucent collection';


    public function handle()
    {
        $name = $this->argument('name');
        $fields = $this->argument('fields');
        $fieldsStringArray = [];
        if(!empty($fields)){
            $fieldsStringArray = explode(',', $fields);
        }


        $schema = new CollectionSchema(
            name: $name,
            label: $name,
            visible: [],
            groups: [],
            fields: Collection::make([]),
            folder: "",
        );
        $schemaAr = $schema->forJsonGenerator();
        $schemaAr["fields"] = collect($fieldsStringArray)
            ->map(fn(string $fieldName) => new Text($fieldName, $fieldName))
            ->map(fn(Text $field) => ["name" => $field->name, "label" => $field->name, "ui" => $field->info->name]);

        $json = json_encode($schemaAr, JSON_PRETTY_PRINT);
        $configDir = base_path(config('lucent.schemas_path'));

        if (!file_exists($configDir)) {
            $this->error("Your config directory \"$configDir\"  doesn't exist. Create it first and run again");
            return;
        }

        $schemaPath = $configDir . "/" . $name . '.json';

        if (file_exists($schemaPath)) {
            $this->error("The schema file already exists.");
            return 0;
        }

        file_put_contents($schemaPath, $json);
        $this->info("The schema file has been created.");

    }

}
