<?php

namespace App\Http\Controllers;

use App\Http\Requests\OfferBulkUpdateIdsRequest;
use App\Http\Requests\OfferBulkUpdateRequest;
use App\Services\OfferBulkUpdateService;
use Illuminate\Http\JsonResponse;

class OfferBulkUpdateController extends Controller
{
    public function getFields(OfferBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'fields' => $service->getFields(),
        ]);
    }

    public function getOfferData(OfferBulkUpdateIdsRequest $request, OfferBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'offers' => $service->getOfferData($request->input('offer_ids')),
        ]);
    }

    public function update(OfferBulkUpdateRequest $request, OfferBulkUpdateService $service): JsonResponse
    {
        $mode = $request->input('mode');
        $offerIds = $request->input('offer_ids');

        $data = $mode === 'same'
            ? ['field' => $request->input('field'), 'value' => $request->input('value')]
            : ['updates' => $request->input('updates', [])];

        $updatedCount = $service->update($mode, $offerIds, $data);

        return response()->json([
            'success' => true,
            'updated_count' => $updatedCount,
            'message' => "{$updatedCount} offer(s) updated successfully.",
        ]);
    }

    public function deleteFinanceExamples(
        OfferBulkUpdateIdsRequest $request,
        OfferBulkUpdateService $service
    ): JsonResponse {
        $deletedCount = $service->deleteFinanceExamples($request->input('offer_ids'));

        return response()->json([
            'success' => true,
            'deleted_count' => $deletedCount,
            'message' => "Finance examples deleted from {$deletedCount} offer(s).",
        ]);
    }
}
