<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreEquipmentRepairRequest;
use App\Services\EquipmentRepairService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EquipmentRepairController extends Controller
{
    public function __construct(
        private EquipmentRepairService $repairService
    ) {}

    public function index(Request $request)
    {
        $repairs = $this->repairService->getRepairs(
            $request->all(),
            $request->input('per_page', 20)
        );

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

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

    public function store(StoreEquipmentRepairRequest $request): JsonResponse
    {
        try {
            $repair = $this->repairService->createRepair($request->validated());

            return response()->json([
                'success' => true,
                'message' => '수리이력이 등록되었습니다.',
                'data' => $repair,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function update(Request $request, int $id): JsonResponse
    {
        try {
            $repair = $this->repairService->updateRepair($id, $request->all());

            return response()->json([
                'success' => true,
                'message' => '수리이력이 수정되었습니다.',
                'data' => $repair,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function destroy(int $id): JsonResponse
    {
        try {
            $this->repairService->deleteRepair($id);

            return response()->json([
                'success' => true,
                'message' => '수리이력이 삭제되었습니다.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
