<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use App\Http\Requests\SavedAdStoreRequest;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class SavedAdsController extends Controller
{
    public function store(SavedAdStoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        $userId = optional($request->user())->id ?? 239053159; // TODO: map telegram user
        try {
            $id = DB::table('saved_ads')->insertGetId([
                'user_id' => $userId,
                'source' => $data['source'],
                'opportunity_id' => $data['opportunity_id'] ?? null,
                'external_source' => $data['external_source'] ?? null,
                'external_code' => $data['external_code'] ?? null,
                'link' => $data['link'] ?? null,
                'created_at' => now(), 'updated_at' => now(),
            ]);
        } catch (\Throwable $e) {
            return response()->json(['error' => 'duplicate', 'message' => 'already saved'], Response::HTTP_CONFLICT);
        }
        // Emit SaveDeal
        try { \App\Services\Analytics\EventBus::track($userId, 'SaveDeal', ['source' => $data['source']]); } catch (\Throwable) {}
        return response()->json(['id' => $id, 'status' => 'saved']);
    }

    public function destroy(int $id): JsonResponse
    {
        $userId = optional(request()->user())->id ?? 239053159;
        $row = DB::table('saved_ads')->where('id',$id)->first();
        if (!$row || $row->user_id != $userId) {
            return response()->json(['error' => 'not_found'], Response::HTTP_NOT_FOUND);
        }
        DB::table('saved_ads')->where('id',$id)->delete();
        return response()->json(['id' => $id, 'status' => 'removed']);
    }

    public function index(): JsonResponse
    {
        $userId = optional(request()->user())->id ?? 239053159;
        $items = DB::table('saved_ads')->where('user_id',$userId)->orderByDesc('id')->limit(50)->get();
        return response()->json(['items' => $items]);
    }
}
