<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\Role;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Role::withCount('users');

        if ($request->keyword) {
            $query->where('name', 'like', "%{$request->keyword}%");
        }

        // 门店角色 + 全局角色
        $user = auth()->user();
        if (!$user->is_super) {
            $query->where(function ($q) use ($user) {
                $q->where('store_id', $user->store_id)
                  ->orWhereNull('store_id');
            });
        }

        $roles = $query->orderByDesc('id')
            ->paginate($request->input('page_size', 20));

        return $this->paginate($roles);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:50',
            'code' => 'required|string|max:50|unique:roles,code',
            'description' => 'nullable|string|max:255',
        ]);

        $user = auth()->user();
        $data['store_id'] = $user->is_super ? null : $user->store_id;

        $role = Role::create($data);
        return $this->success($role, '创建成功');
    }

    public function show(Role $role): JsonResponse
    {
        $role->load('permissions');
        return $this->success($role);
    }

    public function update(Request $request, Role $role): JsonResponse
    {
        if ($role->is_system) {
            return $this->error('系统内置角色不可编辑');
        }

        $data = $request->validate([
            'name' => 'string|max:50',
            'description' => 'nullable|string|max:255',
        ]);

        $role->update($data);
        return $this->success($role, '更新成功');
    }

    /**
     * 分配权限
     */
    public function assignPermissions(Request $request, Role $role): JsonResponse
    {
        $request->validate([
            'permission_ids' => 'required|array',
            'permission_ids.*' => 'exists:permissions,id',
        ]);

        $role->permissions()->sync($request->permission_ids);
        return $this->success(null, '权限分配成功');
    }

    public function destroy(Role $role): JsonResponse
    {
        if ($role->is_system) {
            return $this->error('系统内置角色不可删除');
        }
        if ($role->users()->exists()) {
            return $this->error('该角色下还有用户，无法删除');
        }

        $role->permissions()->detach();
        $role->delete();
        return $this->success(null, '删除成功');
    }
}
