<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionController extends Controller
{
    public function create()
    {
        if (Auth::check() && Auth::user()->email === 'admin@example.com') {
            return redirect()->route('super-admin.tenants.index');
        }
        return view('super-admin.session.login');
    }

    public function store(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            if (Auth::user()->email !== 'admin@example.com') {
                Auth::logout();
                return back()->withErrors([
                    'email' => 'Unauthorized access.',
                ]);
            }

            return redirect()->route('super-admin.tenants.index');
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    public function destroy(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('super-admin.session.create');
    }
}
