<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreNumberingRuleRequest;
use App\Http\Requests\UpdateNumberingRuleRequest;
use App\Services\NumberingRuleService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NumberingRuleController extends Controller
{
    public function __construct(
        private readonly NumberingRuleService $numberingRuleService
    ) {}

    public function index(Request $request): JsonResponse|\Illuminate\View\View
    {
        $rules = $this->numberingRuleService->getRules(
            $request->all(),
            $request->integer('per_page', 20)
        );

        if ($request->header('HX-Request')) {
            return view('numbering.partials.table', compact('rules'));
        }

        return response()->json([
            'success' => true,
            'data' => $rules->items(),
            'meta' => [
                'current_page' => $rules->currentPage(),
                'last_page' => $rules->lastPage(),
                'per_page' => $rules->perPage(),
                'total' => $rules->total(),
            ],
        ]);
    }

    public function store(StoreNumberingRuleRequest $request): JsonResponse
    {
        $rule = $this->numberingRuleService->createRule($request->validated());

        return response()->json([
            'success' => true,
            'message' => '채번 규칙이 생성되었습니다.',
            'redirect' => route('numbering-rules.index'),
            'data' => $rule,
        ], 201);
    }

    public function update(UpdateNumberingRuleRequest $request, int $id): JsonResponse
    {
        $result = $this->numberingRuleService->updateRule($id, $request->validated());

        if (! $result) {
            return response()->json([
                'success' => false,
                'message' => '채번 규칙 수정에 실패했습니다.',
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => '채번 규칙이 수정되었습니다.',
            'redirect' => route('numbering-rules.index'),
        ]);
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $result = $this->numberingRuleService->deleteRule($id);

        if (! $result) {
            return response()->json([
                'success' => false,
                'message' => '채번 규칙 삭제에 실패했습니다.',
            ], 400);
        }

        return response()->json([
            'success' => true,
            'message' => '채번 규칙이 삭제되었습니다.',
            'action' => 'remove',
        ]);
    }

    public function preview(Request $request): JsonResponse
    {
        $pattern = $request->input('pattern', []);
        $sequencePadding = $request->integer('sequence_padding', 2);

        $preview = $this->numberingRuleService->generatePreview($pattern, $sequencePadding);

        return response()->json([
            'success' => true,
            'preview' => $preview,
        ]);
    }
}
