<?php

use Lean\Factory\HttpFactory;

use Ulmus\User\{Entity,
    Lib\Authenticate,
    Middleware\HeaderAuthenticationMiddleware,
    Middleware\PostRequestAuthenticationMiddleware,
    Authorize\PostRequestAuthentication};

use Picea\Picea;

use Storage\{ Cookie, Session };

use function DI\{get, autowire, create};

return [
    Authenticate::class => create(Authenticate::class)->constructor(get(Entity\UserInterface::class), get(Session::class), get(Cookie::class), get('authentication.method')),

    HeaderAuthenticationMiddleware::class => create(HeaderAuthenticationMiddleware::class)->constructor(get(Entity\UserInterface::class), get('authorize.error')),

    PostRequestAuthentication::class => create(PostRequestAuthentication::class)->constructor(get(\Ulmus\User\Lib\Authenticate::class), "email", "email", "password"),

    PostRequestAuthenticationMiddleware::class => create(PostRequestAuthenticationMiddleware::class)->constructor(get(Entity\UserInterface::class), get('authentication.error'), get(PostRequestAuthentication::class)),

    'authentication.method' => null,

    'authorize.error' => function($c) {
        return function(array $errorData) {
            return HttpFactory::createJsonResponse($errorData + [
                'api.error' => "Authorization failed",
                'api.datetime' => (new \DateTime)->format(\DateTime::ATOM),
            ], 401);
        };
    },

    'authentication.error' => function($c, Picea $picea) {
        return function($message) use ($picea) {
            return HttpFactory::createHtmlResponse($picea->renderHtml('lean/error/500', [
                'title' => "Authentication failed",
                'subtitle' => "",
                'message' => $message,
            ]), 401);
        };
    },
];