<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Story;
use App\Models\Friend;
use App\Models\Notification;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\UserShortResource;

class StoryController extends Controller
{
    // Create a story
    public function createStory(Request $request)
    {
        $request->validate([
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:image,video,text',
            'media' => 'nullable|file|max:2048', // Media is nullable for text stories
            'thumbnail' => 'nullable|image|max:2048',
            'duration' => 'nullable|integer',
        ]);

        $data = $request->only(['description', 'type', 'duration']);
        $data['user_id'] = Auth::id();

        // Store media only if present
        if ($request->hasFile('media')) {
            $data['media'] = storeMedia($request->file('media'), 'stories/media');
        } else {
            $data['media'] = null; // No media for text-based stories
        }

        // Store thumbnail if present
        $data['thumbnail'] = $request->hasFile('thumbnail')
            ? storeMedia($request->file('thumbnail'), 'stories/thumbnails')
            : null;

        // Ensure duration is an integer
        $duration = (int) ($data['duration'] ?? (24 * 3600)); // Default to 24 hours if no duration provided

        // Calculate expire_at based on duration
        $data['expire_at'] = now()->addSeconds($duration);

        $story = Story::create($data);

        // Build response structure
        $storyResponse = [
            'id' => $story->id,
            'description' => $story->description,
            'type' => $story->type,
            'duration' => $story->duration,
            'expire_at' => $story->expire_at,
            'media_url' => getMedia($story->media), // Handle null media
            'thumbnail_url' => getMedia($story->thumbnail),
            'user' => new UserShortResource($story->user),
        ];

        return response()->json([
            'status' => 200,
            'message' => 'Story created successfully.',
            'data' => $storyResponse,
        ], 200);
    }
    public function getStories(Request $request)
    {
        $userId = Auth::id();
        $friendIds = Friend::where(function ($query) use ($userId) {
            $query->where('friend_one', $userId)
                ->orWhere('friend_two', $userId);
        })
            ->where('status', 1)
            ->get()
            ->map(function ($friend) use ($userId) {
                return $friend->friend_one == $userId ? $friend->friend_two : $friend->friend_one;
            })
            ->unique();

        $friendIds->prepend($userId);

        $offset = $request->input('offset', 0);
        $limit  = $request->input('limit', 10);

        $stories = Story::with('user')
            ->whereIn('user_id', $friendIds)
            ->where('expire_at', '>', now())
            ->orderByRaw("CASE WHEN user_id = ? THEN 0 ELSE 1 END", [$userId]) // ✅ logged-in first
            ->offset($offset)
            ->limit($limit)
            ->get();

        $stories = $stories->map(function ($story) {
            return [
                'id'            => $story->id,
                'description'   => $story->description,
                'type'          => $story->type,
                'duration'      => $story->duration,
                'expire_at'     => $story->expire_at,
                'media_url'     => getMedia($story->media),
                'thumbnail_url' => $story->thumbnail ? getMedia($story->thumbnail) : null,
                'user'          => new UserShortResource($story->user),
            ];
        });

        return response()->json([
            'status' => 200,
            'data'   => $stories,
        ]);
    }

    public function seenStory(Request $request)
    {
        $request->validate([
            'story_id' => 'required|exists:stories,id',
        ]);
        $loggedinUser = Auth::user();
        $story = Story::findOrFail($request->story_id);
        $story->seenUsers()->syncWithoutDetaching(Auth::id());
        $userdata = User::select('device_id', 'notification_setting')
            ->where('id', $story->user_id)
            ->first(); // Make sure to use first() to get a single result

        if (!empty($userdata) && $loggedinUser->id != $story->user_id) {
            // Decode the JSON column and access the 'notify_like' value
            $notify_liked_page = json_decode(str_replace("\xc2\xa0", ' ', $userdata->notification_setting))->notify_liked_page;
            if ($notify_liked_page == 1) {
                Notification::create([
                    'from_user_id' => Auth::id(),
                    'to_user_id' => $story->user_id,
                    'type' => 'view_story',
                    'text' => 'viewed your story',
                    'story_id' => $story->id,
                ]);
                if (!empty($userdata->device_id)) {
                    sendFirebaseNotification($userdata->device_id, 'Story viewed', $loggedinUser->username . ' viewed your story');
                }
            }
        }

        return response()->json([
            'status' => 200,
            'message' => 'Story marked as seen.',
        ], 200);
    }

    // Get users who have seen a story
    public function storySeenUser($id)
    {
        $story = Story::with('seenUsers')->findOrFail($id);

        // Transform each seen user into a UserShortResource
        $seenUsers = $story->seenUsers->map(function ($user) {
            return new UserShortResource($user);
        });

        return response()->json([
            'status' => 200,
            'data' => $seenUsers,
        ], 200);
    }


    // Delete a story
    public function deleteStory($id)
    {
        $story = Story::findOrFail($id);

        if ($story->user_id !== Auth::id()) {
            return response()->json([
                'status' => 403,
                'message' => 'You are not authorized to delete this story.',
            ], 403);
        }

        $story->delete();

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