<?php

namespace App\Http\Controllers\Admin\System;

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

class PositionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $positions = Position::orderBy('sort')
            ->paginate($request->input('page_size', 50));

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

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

        $data['store_id'] = auth()->user()->store_id;
        $data['sort'] = $data['sort'] ?? 0;
        $position = Position::create($data);
        return $this->success($position, '创建成功');
    }

    public function update(Request $request, Position $position): JsonResponse
    {
        $data = $request->validate([
            'name' => 'string|max:50',
            'code' => 'nullable|string|max:50',
            'sort' => 'nullable|integer',
            'status' => 'in:0,1',
            'description' => 'nullable|string|max:255',
        ]);

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

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