<?php

namespace App\Services;

use App\Models\Listing;
use App\Models\ListingVideo;
use App\Support\Media;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

/**
 * İlan videosu yükleme/silme (consultant + admin controller'ları paylaşır).
 * Dosya MEDIA_DISK'e (R2) yazılır; ilan başına MAX_PER_LISTING sınırı vardır.
 */
class ListingVideoService
{
    public const RULES = [
        'video' => ['required', 'file', 'mimetypes:video/mp4,video/quicktime,video/webm', 'max:204800'], // 200MB
        'title' => ['nullable', 'string', 'max:160'],
        'duration_seconds' => ['nullable', 'integer', 'min:0', 'max:86400'],
    ];

    public function store(Request $request, Listing $listing, UploadedFile $file, ?string $title, ?int $duration): ListingVideo
    {
        if ($listing->videos()->count() >= ListingVideo::MAX_PER_LISTING) {
            throw ValidationException::withMessages([
                'video' => ['Bir ilana en fazla '.ListingVideo::MAX_PER_LISTING.' video eklenebilir.'],
            ]);
        }

        $path = $file->store("listings/{$listing->id}/videos", Media::disk());
        $nextOrder = (int) $listing->videos()->max('sort_order') + 1;

        return ListingVideo::create([
            'listing_id' => $listing->id,
            'file_path' => $path,
            'file_url' => Media::url($request, $path),
            'mime_type' => $file->getClientMimeType(),
            'size' => $file->getSize(),
            'duration_seconds' => $duration,
            'title' => $title ?: pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME),
            'sort_order' => $nextOrder,
        ]);
    }

    public function delete(ListingVideo $video): void
    {
        Storage::disk(Media::disk())->delete($video->file_path);
        $video->delete();
    }

    public function toArray(ListingVideo $video): array
    {
        return [
            'id' => $video->id,
            'file_url' => $video->file_url,
            'mime_type' => $video->mime_type,
            'size' => $video->size,
            'duration_seconds' => $video->duration_seconds,
            'title' => $video->title,
            'sort_order' => $video->sort_order,
            'created_at' => $video->created_at?->toISOString(),
        ];
    }
}
