<?php

namespace App\Http\Controllers\Api\Consultant;

use App\Http\Controllers\Controller;
use App\Models\Listing;
use App\Models\ListingMedia;
use App\Support\Media;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ListingMediaController extends Controller
{
    public function store(Request $request, Listing $listing)
    {
        $this->authorizeOwnership($request, $listing);

        $request->validate([
            'images' => ['required', 'array', 'min:1'],
            'images.*' => ['image', 'mimes:jpeg,jpg,png,webp', 'max:5120'], // 5MB
        ]);

        $hasCover = $listing->media()->where('is_cover', true)->exists();
        $nextOrder = (int) $listing->media()->max('sort_order');

        $created = [];

        foreach ($request->file('images') as $index => $file) {
            // Disk MEDIA_DISK env'inden gelir (canlı: r2, dev: public olabilir).
            $path = $file->store("listings/{$listing->id}", Media::disk());
            $url = Media::url($request, $path);

            $media = ListingMedia::create([
                'listing_id' => $listing->id,
                'file_path' => $path,
                'file_url' => $url,
                'alt_text' => $listing->title,
                'mime_type' => $file->getClientMimeType(),
                'size' => $file->getSize(),
                'sort_order' => ++$nextOrder,
                // İlk yüklenen görsel, henüz kapak yoksa kapak olur.
                'is_cover' => ! $hasCover && $index === 0,
            ]);

            if ($media->is_cover) {
                $hasCover = true;
            }

            $created[] = $this->mediaArray($media);
        }

        return response()->json(['data' => $created], 201);
    }

    public function destroy(Request $request, Listing $listing, ListingMedia $media)
    {
        $this->authorizeOwnership($request, $listing);
        $this->authorizeMedia($listing, $media);

        Storage::disk(Media::disk())->delete($media->file_path);
        $wasCover = $media->is_cover;
        $media->delete();

        // Kapak silindiyse kalan ilk görseli kapak yap.
        if ($wasCover) {
            $next = $listing->media()->orderBy('sort_order')->first();
            $next?->update(['is_cover' => true]);
        }

        return response()->json(['message' => 'Görsel silindi.']);
    }

    public function setCover(Request $request, Listing $listing, ListingMedia $media)
    {
        $this->authorizeOwnership($request, $listing);
        $this->authorizeMedia($listing, $media);

        $listing->media()->update(['is_cover' => false]);
        $media->update(['is_cover' => true]);

        return response()->json(['message' => 'Kapak görseli güncellendi.']);
    }

    private function mediaArray(ListingMedia $media): array
    {
        return [
            'id' => $media->id,
            'file_path' => $media->file_path,
            'file_url' => $media->file_url,
            'alt_text' => $media->alt_text,
            'sort_order' => $media->sort_order,
            'is_cover' => $media->is_cover,
        ];
    }

    private function authorizeOwnership(Request $request, Listing $listing): void
    {
        $profile = $request->user()->consultantProfile;

        abort_unless($profile, 403, 'Danışman profiliniz bulunmuyor.');
        abort_unless($listing->consultant_profile_id === $profile->id, 403, 'Bu ilan üzerinde yetkiniz yok.');
    }

    private function authorizeMedia(Listing $listing, ListingMedia $media): void
    {
        abort_unless($media->listing_id === $listing->id, 404, 'Görsel bulunamadı.');
    }
}
