<?php

namespace app\controller;

use app\service\AdminAuthService;
use support\Request;
use support\Response;

class AdminController
{
    public function landing(Request $request): Response
    {
        if ((new AdminAuthService())->current($request) !== null) {
            return $this->redirect('/admin');
        }

        return view('admin/landing', [
            'archiveCaskUrl' => config('admin.archive_cask_url', ''),
            'version' => $this->version(),
        ]);
    }

    public function login(Request $request): Response
    {
        if ((new AdminAuthService())->current($request) !== null) {
            return $this->redirect('/admin');
        }

        return view('admin/login', [
            'archiveCaskUrl' => config('admin.archive_cask_url', ''),
            'version' => $this->version(),
        ]);
    }

    public function dashboard(Request $request): Response
    {
        $admin = (new AdminAuthService())->current($request);
        if ($admin === null) {
            return $this->redirect('/admin/login');
        }

        return view('admin/dashboard', [
            'archiveCaskUrl' => config('admin.archive_cask_url', ''),
            'admin' => $admin,
            'version' => $this->version(),
        ]);
    }

    private function redirect(string $location): Response
    {
        return response('', 302, ['Location' => $location]);
    }

    private function version(): string
    {
        $path = base_path('.version');
        if (!is_file($path)) {
            return 'unknown';
        }

        $value = trim((string) file_get_contents($path));
        return $value !== '' ? $value : 'unknown';
    }
}
