<?php

namespace AuthStack\UserDirectory\Http\Controllers;

use AuthStack\UserDirectory\Exceptions\AccountException;
use AuthStack\UserDirectory\Http\Requests\Account\Auth;
use AuthStack\UserDirectory\Model\Account as AccountModel;
use Illuminate\Http\JsonResponse;

class Account extends Controller
{
    public function authenticate(Auth $request)
    {
        $result = $this->account()->authenticate($request);
    }

    public function create()
    {}

    public function read()
    {}

    public function update()
    {}

    /**
     * @param $id
     * @return JsonResponse
     */
    public function delete($id): JsonResponse
    {
        $model = $this->account($id);

        $result = $model->delete();

        // @todo: Log that account was deleted

        // Send response
        return response()->json(['result' => $result, 'id' => $id]);
    }

    /**
     * @param $id
     * @return AccountModel
     * @throws AccountException
     */
    public function account($id = null): AccountModel
    {
        try
        {
            if(is_null($id))
            {
                return new AccountModel();
            }

            $user = (new AccountModel())->findOrFail($id);

            return $user;
        }
        catch(\Exception $e)
        {
            throw new AccountException($e->getMessage(), 404, $e);
        }
    }
}
