<?php

namespace App\Http\Controllers;

use App\Http\Requests\ImportBlogXmlRequest;
use App\Jobs\WordPressBlogImport;
use App\Models\BulkImportLog;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Template;

class WordPressBlogImportController extends Controller
{
    public function import(ImportBlogXmlRequest $request): array
    {
        $template = Template::query()->where('slug', 'blog-article')->first();

        if (!$template) {
            return [
                'success' => false,
                'message' => 'Template "blog-article" not found. Please create the template before importing.',
            ];
        }

        $xmlContent = $request->file('file')->getContent();
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($xmlContent, 'SimpleXMLElement', LIBXML_NOCDATA);
        libxml_clear_errors();

        if ($xml === false) {
            return [
                'success' => false,
                'message' => 'Failed to parse the XML file. Please check the file is valid WordPress export XML.',
            ];
        }

        $tmpName = 'blog-import-' . Str::random(8) . '-' . Carbon::now()->format('Y_m_d_H_i_s') . '.xml';
        $pathToFile = 'blog-import/' . $tmpName;

        Storage::disk('file-storage')->put($pathToFile, $xmlContent);

        BulkImportLog::query()->create([
            'user_id' => Auth::id(),
            'object_type' => 'blog',
            'filename' => $pathToFile,
        ]);

        WordPressBlogImport::dispatch($pathToFile);

        return [
            'success' => true,
            'message' => 'Blog import has been queued for processing.',
        ];
    }
}
