<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\ProfileSubscriptions;
use Illuminate\Http\Request;

class ProfileSubscriptionController extends Controller
{
    public function index(Request $request)
    {
        $user = $this->is_user($request);

        $subscriptions = ProfileSubscriptions::query()
            ->where('user_id', $user->id)
            ->with(['subscribable', 'subscribable.user', 'subscribable.listing', 'subscribable.listing.coverImage'])
            ->latest()
            ->get();


        return response()->json([
            'data' => $subscriptions
        ]);
    }


    public function store(Request $request, string $type, int $id)
    {
        $user = $this->is_user($request);

        $data = $request->validate([
            'notify_new_listing' => ['boolean', 'required'],
            'notify_price_drops' => ['boolean', 'required']
        ]);

        $subscription = ProfileSubscriptions::updateOrCreate(
            [
                'user_id' => $user->id,
                'subscribable_type' => $type,
                'subscribable_id' => $id
            ],
            [
                'notify_new_listing' => $data['notify_new_listing'],
                'notify_price_drops' => $data['notify_price_drops']
            ]
        );

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

    public function destroy(Request $request,string $type, int $id)
    {
        $user = $this->is_user($request);

        $subscription = ProfileSubscriptions::query()
        ->where('user_id',$user->id)
        ->where('subscribable_type',$type)
        ->where('subscribable_id',$id)
        ->delete();

        return response()->json([
            'message' => 'subscription is cancelled'
        ]);

    }




    private function is_user(Request $request)
    {
        $user = $request->user();

        abort_unless($user, 403, 'Aboneliklerinizi görüntülemek için giriş yapınız');

        return $user;
    }
}
