<?php

namespace App\Http\Controllers\Api\Posts;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\PostReport;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class PostReportController extends Controller
{
    /**
     * POST /api/posts/{id}/report
     * payload: { reason, message? }
     */
    public function store(Request $request, int $id): JsonResponse
    {
        $user = $request->user();
        $post = Post::findOrFail($id);

        Gate::authorize('report', $post);

        $request->validate([
            'reason'  => ['required', 'string', 'max:64'],
            'message' => ['nullable', 'string', 'max:1000'],
        ]);

        // Unique report per user+post
        $existing = PostReport::where('post_id', $post->id)
            ->where('reporter_user_id', $user->id)
            ->exists();

        if ($existing) {
            return response()->json(['message' => 'You have already reported this post.'], 409);
        }

        PostReport::create([
            'post_id'          => $post->id,
            'reporter_user_id' => $user->id,
            'reason'           => $request->input('reason'),
            'message'          => $request->input('message'),
            'status'           => 'open',
        ]);

        return response()->json(['message' => 'Report submitted. Thank you for helping keep Skinbase safe.'], 201);
    }
}
