<?php

namespace App\Category\Controller;

use App\Category\Service\CategoryImporter;
use App\Shared\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use OpenApi\Attributes as OA;

/**
 * Bulk JSON export/import for the admin "دسته‌بندی‌ها" page (all six tabs).
 *
 * Thin HTTP layer over {@see CategoryImporter}, which holds the strict
 * validation + wipe-and-replace logic shared with the `app:seed-categories`
 * console command.
 *
 *  - Strict two-phase validation: the WHOLE file is validated first; if any
 *    row is invalid, nothing is written and every error is returned (HTTP 422).
 *  - Wipe + full replace, preserving raw `id`s so relations stay intact, inside
 *    one transaction with FK checks disabled.
 */
#[OA\Tag(name: 'Categories')]
#[IsGranted('ROLE_ADMIN')]
class CategoryImportController extends BaseController
{
    public function __construct(
        private readonly CategoryImporter $importer,
    ) {}

    /**
     * Complete export of a bundle — EVERY row, no pagination cap. The page's old
     * "خروجی JSON" button pointed at the admin list endpoint (caps at 100 rows);
     * feeding that truncated file into the wipe+replace import below deletes the
     * tail. This endpoint returns the full table so the round-trip is lossless.
     */
    #[Route('/api/v1/admin/categories/{bundle}/export', methods: ['GET'])]
    public function export(string $bundle): JsonResponse
    {
        if (!$this->importer->isValidBundle($bundle)) {
            return $this->error('ERR_BUNDLE_UNKNOWN', 'نوع دسته‌بندی نامعتبر است', 404, 'bundle');
        }

        return $this->success($this->importer->exportAll($bundle));
    }

    #[Route('/api/v1/admin/categories/{bundle}/import', methods: ['POST'])]
    public function import(string $bundle, Request $request): JsonResponse
    {
        if (!$this->importer->isValidBundle($bundle)) {
            return $this->error('ERR_BUNDLE_UNKNOWN', 'نوع دسته‌بندی نامعتبر است', 404, 'bundle');
        }

        $payload = json_decode($request->getContent(), true);
        // accept both a raw array and { "items": [...] }
        if (is_array($payload) && isset($payload['items']) && is_array($payload['items'])) {
            $payload = $payload['items'];
        }
        if (!is_array($payload) || $payload === [] || array_keys($payload) !== range(0, count($payload) - 1)) {
            return $this->error('ERR_IMPORT_FORMAT', 'فایل باید یک آرایه‌ی غیرخالی از رکوردها باشد', 422, 'file');
        }
        if (count($payload) > 5000) {
            return $this->error('ERR_IMPORT_TOO_LARGE', 'حداکثر ۵۰۰۰ رکورد در هر import مجاز است', 422, 'file');
        }

        $normalized = [];
        $errors = $this->importer->validate($bundle, $payload, $normalized);
        if ($errors !== []) {
            return new JsonResponse(['success' => false, 'data' => null, 'errors' => $errors], 422);
        }

        try {
            $this->importer->replace($bundle, $normalized);
        } catch (\Throwable $e) {
            return $this->error('ERR_IMPORT_FAILED', 'خطا در ذخیره‌سازی: ' . $e->getMessage(), 500);
        }

        return $this->success(['imported' => count($normalized)]);
    }
}
