<?php

namespace Lucent\Http\Controller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Lucent\Account\AccountService;
use Lucent\Account\AuthService;
use Lucent\LucentException;
use Lucent\Svelte\Svelte;
use function Lucent\Response\fail;

class MemberController extends Controller
{
    public function __construct(
        private readonly AuthService    $authService,
        private readonly AccountService $accountService,
        private readonly Svelte         $svelte,
    )
    {

    }

    public function index()
    {

        return $this->svelte->render(
            layout: "channel",
            view: "members",
            title: "Members",
            data: [
                "users" => $this->accountService->allProfiles()->toArray(),
            ]
        );
    }

    public function invite(Request $request)
    {
        if (empty($request->input("roles"))) {
            return fail("Select a role for the user");
        }

        try {
            $user = $this->authService->invite($request->input("name"), $request->input("email"), $request->input("roles"));
        } catch (LucentException $th) {
            return fail($th);
        }

        return [
            "user" => $user
        ];
    }

    public function update(Request $request)
    {
        try {
            $this->authService->changeRoles($request->input("id"), $request->input("roles"));
        } catch (LucentException $th) {
            return fail($th);
        }

        return [
            "users" => $this->accountService->allProfiles()->toArray(),
        ];
    }


}
