<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreEquipmentRequest;
use App\Http\Requests\UpdateEquipmentRequest;
use App\Services\EquipmentImportService;
use App\Services\EquipmentPhotoService;
use App\Services\EquipmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EquipmentController extends Controller
{
    public function __construct(
        private EquipmentService $equipmentService,
        private EquipmentPhotoService $photoService,
        private EquipmentImportService $importService,
    ) {}

    public function index(Request $request)
    {
        $equipments = $this->equipmentService->getEquipments(
            $request->all(),
            $request->input('per_page', 20)
        );

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

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

    public function store(StoreEquipmentRequest $request): JsonResponse
    {
        try {
            $equipment = $this->equipmentService->createEquipment($request->validated());

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

    public function show(int $id): JsonResponse
    {
        $equipment = $this->equipmentService->getEquipmentById($id);

        if (! $equipment) {
            return response()->json([
                'success' => false,
                'message' => '설비를 찾을 수 없습니다.',
            ], 404);
        }

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

    public function update(UpdateEquipmentRequest $request, int $id): JsonResponse
    {
        try {
            $equipment = $this->equipmentService->updateEquipment($id, $request->validated());

            return response()->json([
                'success' => true,
                'message' => '설비 정보가 수정되었습니다.',
                'data' => $equipment,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

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

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

    public function restore(int $id): JsonResponse
    {
        try {
            $this->equipmentService->restoreEquipment($id);

            return response()->json([
                'success' => true,
                'message' => '설비가 복원되었습니다.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function templates(int $id): JsonResponse
    {
        $equipment = $this->equipmentService->getEquipmentById($id);

        if (! $equipment) {
            return response()->json(['success' => false, 'message' => '설비를 찾을 수 없습니다.'], 404);
        }

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

    // =========================================================================
    // 사진 관리
    // =========================================================================

    public function uploadPhotos(Request $request, int $id): JsonResponse
    {
        $request->validate([
            'photos' => 'required|array|min:1|max:10',
            'photos.*' => 'required|image|max:10240',
        ]);

        $equipment = $this->equipmentService->getEquipmentById($id);

        if (! $equipment) {
            return response()->json(['success' => false, 'message' => '설비를 찾을 수 없습니다.'], 404);
        }

        $result = $this->photoService->uploadPhotos($equipment, $request->file('photos'));

        return response()->json([
            'success' => true,
            'message' => "{$result['uploaded']}장 업로드 완료",
            'data' => [
                'uploaded' => $result['uploaded'],
                'errors' => $result['errors'],
                'photos' => $this->photoService->getPhotoUrls($equipment),
            ],
        ]);
    }

    public function photos(int $id): JsonResponse
    {
        $equipment = $this->equipmentService->getEquipmentById($id);

        if (! $equipment) {
            return response()->json(['success' => false, 'message' => '설비를 찾을 수 없습니다.'], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $this->photoService->getPhotoUrls($equipment),
        ]);
    }

    public function deletePhoto(int $id, int $fileId): JsonResponse
    {
        $equipment = $this->equipmentService->getEquipmentById($id);

        if (! $equipment) {
            return response()->json(['success' => false, 'message' => '설비를 찾을 수 없습니다.'], 404);
        }

        $deleted = $this->photoService->deletePhoto($equipment, $fileId);

        if (! $deleted) {
            return response()->json(['success' => false, 'message' => '사진을 찾을 수 없습니다.'], 404);
        }

        return response()->json([
            'success' => true,
            'message' => '사진이 삭제되었습니다.',
        ]);
    }

    // =========================================================================
    // 엑셀 Import
    // =========================================================================

    public function importPreview(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
        ]);

        try {
            $result = $this->importService->preview($request->file('file')->getRealPath());

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function importExecute(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls|max:10240',
            'duplicate_action' => 'in:skip,overwrite',
        ]);

        try {
            $result = $this->importService->import(
                $request->file('file')->getRealPath(),
                ['duplicate_action' => $request->input('duplicate_action', 'skip')]
            );

            $photoMsg = '';
            if (! empty($result['photos_uploaded'])) {
                $photoMsg = ", 사진 {$result['photos_uploaded']}장 업로드";
            }

            return response()->json([
                'success' => true,
                'message' => "Import 완료: 성공 {$result['success']}건, 실패 {$result['failed']}건, 건너뜀 {$result['skipped']}건{$photoMsg}",
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
