<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ConversationParticipant;
use App\Models\Message;
use App\Models\Report;
use App\Models\Story;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ReportController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();

        $data = $request->validate([
            'target_type' => 'required|in:message,conversation,user,story',
            'target_id' => 'required|integer|min:1',
            'reason' => 'required|string|max:120',
            'details' => 'nullable|string|max:4000',
        ]);

        $targetType = $data['target_type'];
        $targetId = (int) $data['target_id'];

        if ($targetType === 'message') {
            $message = Message::query()->findOrFail($targetId);
            $allowed = ConversationParticipant::query()
                ->where('conversation_id', $message->conversation_id)
                ->where('user_id', $user->id)
                ->whereNull('left_at')
                ->exists();
            abort_unless($allowed, 403, 'You are not allowed to report this message.');
        }

        if ($targetType === 'conversation') {
            $allowed = ConversationParticipant::query()
                ->where('conversation_id', $targetId)
                ->where('user_id', $user->id)
                ->whereNull('left_at')
                ->exists();
            abort_unless($allowed, 403, 'You are not allowed to report this conversation.');
        }

        if ($targetType === 'user') {
            User::query()->findOrFail($targetId);
        }

        if ($targetType === 'story') {
            Story::query()->findOrFail($targetId);
        }

        $report = Report::query()->create([
            'reporter_id' => $user->id,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'reason' => $data['reason'],
            'details' => $data['details'] ?? null,
            'status' => 'open',
        ]);

        return response()->json(['id' => $report->id, 'status' => $report->status], 201);
    }
}
