<?php

namespace App\Http\Controllers\Juil;

use App\Helpers\AiTokenHelper;
use App\Http\Controllers\Controller;
use App\Models\Juil\ConstructionSitePhoto;
use App\Models\Juil\ConstructionSitePhotoRow;
use App\Services\ConstructionSitePhotoService;
use App\Services\GoogleCloudService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;

class ConstructionSitePhotoController extends Controller
{
    public function __construct(
        private readonly ConstructionSitePhotoService $service
    ) {}

    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('juil.construction-photos.index'));
        }

        return view('juil.construction-photos');
    }

    public function list(Request $request): JsonResponse
    {
        $params = $request->only(['search', 'date_from', 'date_to', 'per_page']);
        $photos = $this->service->getList($params);

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

    public function show(int $id): JsonResponse
    {
        $photo = ConstructionSitePhoto::with(['user', 'rows'])->find($id);

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

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'site_name' => 'required|string|max:200',
            'work_date' => 'required|date',
            'description' => 'nullable|string|max:2000',
        ]);

        $photo = $this->service->create($validated);

        return response()->json([
            'success' => true,
            'message' => '사진대지가 등록되었습니다.',
            'data' => $photo,
        ], 201);
    }

    public function uploadPhoto(Request $request, int $id, int $rowId): JsonResponse
    {
        $photo = ConstructionSitePhoto::find($id);

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

        $row = ConstructionSitePhotoRow::where('id', $rowId)
            ->where('construction_site_photo_id', $id)
            ->first();

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

        $validated = $request->validate([
            'type' => 'required|in:before,during,after',
            'photo' => 'required|image|mimes:jpeg,jpg,png,webp|max:10240',
        ]);

        $result = $this->service->uploadPhoto($row, $request->file('photo'), $validated['type']);

        if (! $result) {
            return response()->json([
                'success' => false,
                'message' => '사진 업로드에 실패했습니다.',
            ], 500);
        }

        return response()->json([
            'success' => true,
            'message' => '사진이 업로드되었습니다.',
            'data' => $photo->fresh()->load('rows'),
        ]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $photo = ConstructionSitePhoto::find($id);

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

        $validated = $request->validate([
            'site_name' => 'required|string|max:200',
            'work_date' => 'required|date',
            'description' => 'nullable|string|max:2000',
        ]);

        $photo = $this->service->update($photo, $validated);

        return response()->json([
            'success' => true,
            'message' => '사진대지가 수정되었습니다.',
            'data' => $photo,
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $photo = ConstructionSitePhoto::with('rows')->find($id);

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

        $this->service->delete($photo);

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

    public function deletePhoto(int $id, int $rowId, string $type): JsonResponse
    {
        $photo = ConstructionSitePhoto::find($id);

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

        $row = ConstructionSitePhotoRow::where('id', $rowId)
            ->where('construction_site_photo_id', $id)
            ->first();

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

        if (! in_array($type, ['before', 'during', 'after'])) {
            return response()->json([
                'success' => false,
                'message' => '올바르지 않은 사진 유형입니다.',
            ], 422);
        }

        $this->service->deletePhotoByType($row, $type);

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

    public function downloadPhoto(Request $request, int $id, int $rowId, string $type): Response|JsonResponse
    {
        $photo = ConstructionSitePhoto::find($id);

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

        $row = ConstructionSitePhotoRow::where('id', $rowId)
            ->where('construction_site_photo_id', $id)
            ->first();

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

        if (! in_array($type, ['before', 'during', 'after'])) {
            return response()->json([
                'success' => false,
                'message' => '올바르지 않은 사진 유형입니다.',
            ], 422);
        }

        $path = $row->{$type.'_photo_path'};

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

        $googleCloudService = app(GoogleCloudService::class);
        $content = $googleCloudService->downloadFromStorage($path);

        if (! $content) {
            return response()->json([
                'success' => false,
                'message' => '파일 다운로드에 실패했습니다.',
            ], 500);
        }

        $extension = pathinfo($path, PATHINFO_EXTENSION) ?: 'jpg';
        $mimeType = 'image/'.($extension === 'jpg' ? 'jpeg' : $extension);

        $typeLabel = match ($type) {
            'before' => '작업전',
            'during' => '작업중',
            'after' => '작업후',
        };
        $safeTitle = preg_replace('/[\/\\\\:*?"<>|]/', '_', $photo->site_name);
        $filename = "{$safeTitle}_{$typeLabel}.{$extension}";
        $encodedFilename = rawurlencode($filename);

        $disposition = $request->query('inline') ? 'inline' : 'attachment';

        return response($content)
            ->header('Content-Type', $mimeType)
            ->header('Content-Length', strlen($content))
            ->header('Accept-Ranges', 'bytes')
            ->header('Content-Disposition', "{$disposition}; filename=\"{$encodedFilename}\"; filename*=UTF-8''{$encodedFilename}")
            ->header('Cache-Control', 'private, max-age=3600');
    }

    public function addRow(int $id): JsonResponse
    {
        $photo = ConstructionSitePhoto::find($id);

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

        $this->service->addRow($photo);

        return response()->json([
            'success' => true,
            'message' => '사진 행이 추가되었습니다.',
            'data' => $photo->fresh()->load('rows'),
        ]);
    }

    public function deleteRow(int $id, int $rowId): JsonResponse
    {
        $photo = ConstructionSitePhoto::with('rows')->find($id);

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

        if ($photo->rows->count() <= 1) {
            return response()->json([
                'success' => false,
                'message' => '최소 1개의 사진 행은 유지해야 합니다.',
            ], 422);
        }

        $row = $photo->rows->firstWhere('id', $rowId);

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

        $this->service->deleteRow($row);

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

    public function logSttUsage(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'duration_seconds' => 'required|integer|min:1',
        ]);

        AiTokenHelper::saveSttUsage('공사현장사진대지-음성입력', $validated['duration_seconds']);

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