<?php

namespace App\Http\Controllers;

use App\Http\Requests\ImportBlogRequest;
use App\Imports\Blog\CsvBlogParser;
use App\Imports\Blog\WordPressXmlParser;
use App\Jobs\BlogImportJob;
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 BlogImportController extends Controller
{
    private const MAPPABLE_FIELD_TYPES = [
        'text',
        'email',
        'number',
        'datetime',
        'editor',
        'image',
        'select',
        'boolean',
    ];

    public function import(ImportBlogRequest $request): array
    {
        $templateSlug = Template::query()->findOrFail($request->input('template_id'))->slug;

        $format = $request->input('format');
        $file = $request->file('file');

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

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

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

        $parserClass = match ($format) {
            'wordpress' => WordPressXmlParser::class,
            'csv' => CsvBlogParser::class,
        };

        $parserConfig = match ($format) {
            'wordpress' => [
                'templateSlug' => $templateSlug,
                'defaultPageCategory' => $request->input('page_category') ?: null,
            ],
            'csv' => [
                'columnMapping' => $request->input('column_mapping'),
                'contentElementMapping' => $request->input('content_element_mapping', []),
                'templateSlug' => $templateSlug,
                'dateFormat' => $request->input('date_format') ?: 'd/m/Y',
                'defaultPageCategory' => $request->input('page_category') ?: null,
            ],
        };

        BlogImportJob::dispatch($pathToFile, $parserClass, $parserConfig);

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

    public function templateElements(Template $template): array
    {
        $template->load([
            'elements.element.fields' => fn ($query) => $query
                ->whereIn('field_type', self::MAPPABLE_FIELD_TYPES),
        ]);

        return [
            'elements' => $template->elements
                ->map(fn ($element) => [
                    'id' => $element->id,
                    'name' => $element->name,
                    'fields' => $element->element?->fields
                        ->map(fn ($field) => [
                            'slug' => $field->slug,
                            'name' => $field->name,
                            'field_type' => $field->field_type,
                        ])
                        ->values()
                        ->all()
                        ?? [],
                ])
                ->filter(fn ($element) => !empty($element['fields']))
                ->values()
                ->all(),
        ];
    }
}
