<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Ad;
use App\Models\AdReport;

class AdReportingController extends Controller
{
    /**
     * Store a newly created ad report.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $adId
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request, $adId)
    {
        $request->validate([
            'reason' => 'required|string|in:scam,fake,inappropriate,duplicate,other',
            'description' => 'nullable|string|max:1000',
        ]);

        $ad = Ad::find($adId);

        if (!$ad) {
            return response()->json(['message' => 'Ad not found'], 404);
        }

        // Prevent double reporting by same user
        $existingReport = AdReport::where('ad_id', $adId)
            ->where('reporter_id', auth()->id())
            ->first();

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

        // Create Report
        AdReport::create([
            'ad_id' => $adId,
            'reporter_id' => auth()->id(),
            'reason' => $request->reason,
            'description' => $request->description,
            'status' => 'pending'
        ]);

        // AUTOMATION: Check for high volume of reports
        $reportCount = AdReport::where('ad_id', $adId)->distinct('reporter_id')->count();

        if ($reportCount >= 5 && $ad->status !== 'suspended') {
            // Auto-suspend the ad
            $ad->update(['status' => 'suspended']);

            // Update all pending reports for this ad
            AdReport::where('ad_id', $adId)
                ->where('status', 'pending')
                ->update([
                    'status' => 'resolved',
                    'action_taken' => 'auto_suspended',
                    'admin_notes' => 'Auto-suspended due to high report volume (>5 reported users).'
                ]);

            // TODO: Notify Ad Owner about suspension
        }

        return response()->json(['message' => 'Ad reported successfully. We will review it shortly.'], 201);
    }
}
