<?php

namespace App\Http\Middleware;

use App\Models\Admin;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SiteAdminAuth
{
    public function handle(Request $request, Closure $next): Response
    {
        $adminId = $request->session()->get('admin_id');

        if (! $adminId) {
            return redirect('/site-admin/login');
        }

        $admin = Admin::query()->with('merchant')->find($adminId);

        if (! $admin || ! $admin->isMerchantAdmin()) {
            abort(403, '当前账号未绑定站点后台访问权限');
        }

        $request->session()->put('admin_scope', 'site');
        $request->session()->put('admin_role', $admin->role);
        $request->session()->put('admin_name', $admin->name);
        $request->session()->put('admin_email', $admin->email);
        $request->session()->put('admin_merchant_id', $admin->merchantId());
        $request->session()->put('admin_site_id', $admin->merchantId());
        $request->session()->put('site_name', $admin->merchant?->name);

        return $next($request);
    }
}
