<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Story;
use App\Models\ContentCreator;
use Illuminate\Support\Facades\Storage;

class StoryController extends Controller
{
    // 🟢 View other content creators' stories (not own)
    public function index()
    {
        $creator = ContentCreator::where('user_id', auth()->id())->first();

        if (!$creator) {
            return response()->json(['message' => 'You are not a content creator.'], 403);
        }

        $stories = Story::with('creator.user')
            ->where('content_creator_id', '!=', $creator->id)
            ->where('expires_at', '>', now())
            ->latest()
            ->get();

        return response()->json($stories);
    }

    // 🟢 Upload a story
    public function store(Request $request)
    {
        $request->validate([
            'media' => 'required|file|mimes:jpg,jpeg,png,mp4|max:10240',
            'caption' => 'nullable|string|max:255',
        ]);

        $creator = ContentCreator::where('user_id', auth()->id())->first();

        if (!$creator || !$creator->isEligible()) {
            return response()->json(['message' => 'You are not eligible to post stories.'], 403);
        }

        $path = $request->file('media')->store('stories', 'public');

        $story = Story::create([
            'content_creator_id' => $creator->id,
            'media_path' => $path,
            'caption' => $request->caption,
            'expires_at' => now()->addHours(24), // expires in 24 hours
        ]);

        return response()->json([
            'message' => 'Story uploaded successfully!',
            'story' => $story,
        ]);
    }

    // 🔴 Delete own story
    public function destroy($id)
    {
        $creator = ContentCreator::where('user_id', auth()->id())->first();

        $story = Story::where('id', $id)->where('content_creator_id', $creator->id)->first();

        if (!$story) {
            return response()->json(['message' => 'Story not found or unauthorized.'], 404);
        }

        // Delete media file
        Storage::disk('public')->delete($story->media_path);

        $story->delete();

        return response()->json(['message' => 'Story deleted.']);
    }
}
