<?php

/**
 * 文件功能：后台部门管理控制器
 * 提供部门的 CRUD 功能（增删改查）
 * 部门是职务的上级分类，包含位阶、颜色、描述等配置
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Department;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DepartmentController extends Controller
{
    /**
     * 部门列表页
     */
    public function index(): View
    {
        $departments = Department::withCount(['positions'])
            ->orderBy('sort_order')
            ->orderByDesc('rank')
            ->get();

        return view('admin.departments.index', compact('departments'));
    }

    /**
     * 创建部门
     */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:50|unique:departments,name',
            'rank' => 'required|integer|min:0|max:99',
            'color' => 'required|string|max:10',
            'sort_order' => 'required|integer|min:0',
            'description' => 'nullable|string|max:255',
        ]);

        Department::create($data);

        return redirect()->route('admin.departments.index')->with('success', "部门【{$data['name']}】创建成功！");
    }

    /**
     * 更新部门
     */
    public function update(Request $request, Department $department): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:50|unique:departments,name,'.$department->id,
            'rank' => 'required|integer|min:0|max:99',
            'color' => 'required|string|max:10',
            'sort_order' => 'required|integer|min:0',
            'description' => 'nullable|string|max:255',
        ]);

        $department->update($data);

        return redirect()->route('admin.departments.index')->with('success', "部门【{$data['name']}】更新成功！");
    }

    /**
     * 删除部门（级联删除职务）
     */
    public function destroy(Department $department): RedirectResponse
    {
        // 检查是否有在职人员
        $activeMemberCount = $department->positions()
            ->whereHas('activeUserPositions')
            ->count();

        if ($activeMemberCount > 0) {
            return redirect()->route('admin.departments.index')
                ->with('error', "部门【{$department->name}】下尚有在职人员，请先撤销所有职务后再删除。");
        }

        $department->delete();

        return redirect()->route('admin.departments.index')->with('success', "部门【{$department->name}】已删除！");
    }
}
