<?php

namespace App\Http\Controllers;

use App\Http\Requests\PageBulkUpdateIdsRequest;
use App\Http\Requests\PageBulkUpdateRequest;
use App\Services\PageBulkUpdateService;
use Illuminate\Http\JsonResponse;

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

    public function getPageData(PageBulkUpdateIdsRequest $request, PageBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'pages' => $service->getPageData($request->input('page_ids')),
        ]);
    }

    public function update(PageBulkUpdateRequest $request, PageBulkUpdateService $service): JsonResponse
    {
        $mode = $request->input('mode');
        $pageIds = $request->input('page_ids');

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

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

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

    public function archive(PageBulkUpdateIdsRequest $request, PageBulkUpdateService $service): JsonResponse
    {
        $archivedCount = $service->archive($request->input('page_ids'));

        return response()->json([
            'success' => true,
            'archived_count' => $archivedCount,
            'message' => "{$archivedCount} page(s) archived successfully.",
        ]);
    }
}
