<?php

namespace App\Http\Controllers\Admin\System;

use App\Http\Controllers\Controller;
use App\Models\System\RegistrationPackage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RegistrationPackageController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $packages = RegistrationPackage::when($request->keyword, fn($q) =>
                $q->where('name', 'like', "%{$request->keyword}%"))
            ->when($request->has('status'), fn($q) =>
                $q->where('status', $request->status))
            ->orderBy('sort')->orderByDesc('id')
            ->paginate($request->input('page_size', 20));

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

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'        => 'required|string|max:50',
            'description' => 'nullable|string|max:255',
            'role_ids'    => 'array',
            'role_ids.*'  => 'exists:roles,id',
            'status'      => 'in:0,1',
            'sort'        => 'integer|min:0',
        ]);

        $data['store_id'] = auth()->user()->store_id;
        $package = RegistrationPackage::create($data);

        return $this->success($package, '创建成功');
    }

    public function show(RegistrationPackage $registrationPackage): JsonResponse
    {
        return $this->success($registrationPackage);
    }

    public function update(Request $request, RegistrationPackage $registrationPackage): JsonResponse
    {
        $data = $request->validate([
            'name'        => 'string|max:50',
            'description' => 'nullable|string|max:255',
            'role_ids'    => 'array',
            'role_ids.*'  => 'exists:roles,id',
            'status'      => 'in:0,1',
            'sort'        => 'integer|min:0',
        ]);

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

    public function destroy(RegistrationPackage $registrationPackage): JsonResponse
    {
        $registrationPackage->delete();
        return $this->success(null, '删除成功');
    }
}
