<?php

namespace App\Services;

use App\Http\Responses\ApiResponse;
use App\Models\UserGroup;
use Illuminate\Support\Facades\DB;

class UserGroupService
{
    public function index(array $params)
    {
        $query = UserGroup::query();

        if (isset($params['keyword']) && ! empty($params['keyword'])) {
            $query->where(function ($q) use ($params) {
                $q->where('name', 'like', "%{$params['keyword']}%")
                    ->orWhere('code', 'like', "%{$params['keyword']}%");
            });
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        $perPage = $params['per_page'] ?? config('cmspro.pagination.per_page', 15);
        $groups = $query->orderBy('sort', 'asc')->orderBy('id', 'desc')->paginate($perPage);

        return ApiResponse::paginate($groups);
    }

    public function store(array $data)
    {
        $exists = UserGroup::where('code', $data['code'])->exists();
        if ($exists) {
            return ApiResponse::error(60101, '用户组标识已存在');
        }

        $group = UserGroup::create([
            'name' => $data['name'],
            'code' => $data['code'],
            'description' => $data['description'] ?? null,
            'icon' => $data['icon'] ?? null,
            'color' => $data['color'] ?? null,
            'is_default' => $data['is_default'] ?? 0,
            'sort' => $data['sort'] ?? 0,
            'status' => $data['status'] ?? 1,
        ]);

        if ($group->is_default) {
            $this->resetOtherDefaults($group->id);
        }

        return ApiResponse::success($group, '创建成功');
    }

    public function show(int $id)
    {
        $group = UserGroup::withCount('users')->find($id);

        if (! $group) {
            return ApiResponse::error(60102, '用户组不存在');
        }

        return ApiResponse::success($group);
    }

    public function update(int $id, array $data)
    {
        $group = UserGroup::find($id);

        if (! $group) {
            return ApiResponse::error(60102, '用户组不存在');
        }

        $codeExists = UserGroup::where('code', $data['code'])
            ->where('id', '!=', $id)
            ->exists();
        if ($codeExists) {
            return ApiResponse::error(60101, '用户组标识已存在');
        }

        $updateData = [
            'name' => $data['name'],
            'code' => $data['code'],
            'description' => $data['description'] ?? null,
            'icon' => $data['icon'] ?? null,
            'color' => $data['color'] ?? null,
            'is_default' => $data['is_default'] ?? 0,
            'sort' => $data['sort'] ?? 0,
        ];

        if (isset($data['status'])) {
            $updateData['status'] = $data['status'];
        }

        $group->update($updateData);

        if ($group->is_default) {
            $this->resetOtherDefaults($group->id);
        }

        return ApiResponse::success($group, '更新成功');
    }

    public function destroy(int $id)
    {
        $group = UserGroup::find($id);

        if (! $group) {
            return ApiResponse::error(60102, '用户组不存在');
        }

        if ($group->hasUsers()) {
            return ApiResponse::error(60103, '该用户组下存在用户，无法删除');
        }

        $group->delete();

        return ApiResponse::success(null, '删除成功');
    }

    public function all()
    {
        $groups = UserGroup::enabled()
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->get(['id', 'name', 'code', 'color', 'is_default']);

        return ApiResponse::success($groups);
    }

    private function resetOtherDefaults(int $excludeId): void
    {
        UserGroup::where('id', '!=', $excludeId)
            ->where('is_default', 1)
            ->update(['is_default' => 0]);
    }
}
