<?php

namespace App\Http\Controllers\MerchantAdmin;

use App\Http\Controllers\Concerns\ResolvesMerchantContext;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class AuthController extends Controller
{
    use ResolvesMerchantContext;

    public function showLogin(): View
    {
        return view('merchant_admin.auth.login');
    }

    public function login(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $admin = Admin::query()->where('email', $data['email'])->first();
        if (! $admin || ! Hash::check($data['password'], $admin->password)) {
            return back()->withErrors(['email' => '账号或密码错误'])->withInput();
        }

        if (! $admin->isMerchantAdmin()) {
            return back()->withErrors(['email' => '当前账号不是商家管理员，不能登录商家后台'])->withInput();
        }

        $merchantId = $admin->merchantId();

        $request->session()->put('admin_id', $admin->id);
        $request->session()->put('admin_name', $admin->name);
        $request->session()->put('admin_email', $admin->email);
        $request->session()->put('admin_role', $admin->role);
        $request->session()->put('admin_merchant_id', $merchantId);
        $request->session()->put('admin_scope', 'merchant');
        $request->session()->put('merchant_name', $admin->merchant?->name);

        $admin->forceFill(['last_login_at' => now()])->save();

        return redirect('/merchant-admin');
    }

    public function logout(Request $request): RedirectResponse
    {
        $request->session()->forget(['admin_id', 'admin_name', 'admin_email', 'admin_role', 'admin_merchant_id', 'admin_scope', 'merchant_name']);
        return redirect('/merchant-admin/login');
    }
}
