<?php

namespace Lucent\Http\Controller\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Lucent\Account\AuthService;
use Lucent\Channel\ChannelRepo;
use Lucent\File\FileUploadResult;
use Lucent\Query\Query;
use Lucent\Record\RecordService;
use function Lucent\File\uploadFile;
use function Lucent\Response\fail;
use function Lucent\Response\ok;

class FileController extends Controller
{
    public function __construct(
        private readonly RecordService $recordService,
        private readonly Query         $query
    )
    {
    }

    public function upload(Request $request)
    {
        $validator = Validator::make(request()->all(), [
            'files.*' => 'required|file|max:100000',
        ]);

        if ($validator->fails()) {
            return fail($validator->errors()->first());
        }
        $channel = ChannelRepo::current();
        $schema = $channel->schemas->firstWhere("name", $request->input("schema"));
        $files = request()->file('files');


        $uploadResults = collect($files)->map(fn($file) => uploadFile($schema, $file))->toArray();
        $insertedIds = collect($uploadResults)
            ->filter(fn(FileUploadResult $res) => !$res->isDuplicate)
            ->values()
            ->map(function (FileUploadResult $uploadResult) use ($schema, $request) {


                return $this->recordService->create(
                    userId: AuthService::currentUserId($request),
                    schemaName: $schema->name,
                    data: [],
                    file: (array)$uploadResult->recordFile,
                    edges: [],
                    status: $request->input("status") ?? "published",
                    uploadFromUrl: ""
                );

            })->toArray();


        return ok($insertedIds);
    }
}
