<?php

namespace Lucent\Http\Controller\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Lucent\Schema\SchemaService;
use function Lucent\Response\fail;
use function Lucent\Response\ok;

class SchemaController extends Controller
{
    public function __construct(
        private readonly SchemaService $schemaService
    )
    {
    }
    // public function find(Request $request)
    // {
    //     $cid = $request->header("CHANNEL-ID");
    //     $channelContext = ChannelContext::fromId($cid)->withSchemas();
    //     return ok($channelContext->getSchemas());
    // }

    // public function findOne(Request $request, string $name)
    // {
    //     $cid = $request->header("CHANNEL-ID");
    //     $channelContext = ChannelContext::fromId($cid)->withSchemas();
    //     $schema = SchemaRepo::context($channelContext)->findByName($name);
    //     return ok($schema->toArray());
    // }

    public function create(Request $request)
    {
        try {
            $schema = $this->schemaService->create(
                name: $request->input("name"),
                label: $request->input("label"),
                type: $request->input("type"),
                isEntry: $request->input("isEntry"),
                revisionRetentionDays: $request->input("revisionRetentionDays"),
                revisionRetentionNumber: $request->input("revisionRetentionNumber"),
                trashedRetentionDays: $request->input("trashedRetentionDays"),
                fields: $request->input("fields"),
                titleTemplate: $request->input("titleTemplate") ?? "",
                visible: $request->input("visible") ?? [],
                path: $request->input("path") ?? "",
            );
        } catch (\Throwable $th) {
            return fail($th);
        }

        return ok($schema->toArray());
    }

    // public function update(Request $request)
    // {
    //     $cid = $request->header("CHANNEL-ID");
    //     try {
    //         $channelContext = ChannelContext::fromId($cid);
    //         SchemaRepo::context($channelContext)->update($request->all());
    //     } catch (\Throwable $th) {
    //         return fail($th);
    //     }

    //     $schema = SchemaRepo::context($channelContext)->findByName($request->input("name"));
    //     return ok($schema->toArray());
    // }

    public function delete(Request $request)
    {
        try {
            $this->schemaService->delete($request->route("name"));
        } catch (\Throwable $th) {
            return fail($th);
        }


        return ok();
    }
}
