<?php

use Illuminate\Database\Migrations\Migration;
use Inside\Content\Models\Contents\Forms;
use Inside\Form\Facades\FormFile;
use Inside\Form\Models\FormSubmission;
use Inside\Host\Bridge\BridgeContent;

class FixFormAutoTranslation extends Migration
{
    /**
     *
     */
    public function up(): void
    {
        $submissions = FormSubmission::all();

        /** @var FormSubmission $model */
        foreach ($submissions as $model) {
            $form = $model->answerable;
            $langcode = $form->langcode === 'en' ? 'fr' : 'en';
            $form = $form->getTranslationIfExists($langcode);

            if ($form->langcode !== $langcode) {
                continue;
            }

            $submission = FormSubmission::query()->where([
                'user_uuid' => $model->user_uuid,
                'answerable_uuid' => $form->uuid,
                'created_at' => date('Y-m-d H:i:s', $model->created_at)
            ])->first();

            if ($submission) {
                continue;
            }

            $formSubmission = FormSubmission::create(
                [
                    "answerable_uuid" => $form->uuid,
                    "answerable_type" => Forms::class,
                    "user_uuid"       => $model->user_uuid,
                    "created_at" => date('Y-m-d H:i:s', $model->created_at),
                ]
            );

            $formAnswers = [];

            foreach ($model->answers as $answer) {
                $answer = $answer->toArray();
                if ($answer['field_type'] === 'input-attachment') {
                    $answer['answer'] = !empty($answer['answer']) ? FormFile::saveFile($formSubmission->id, $form->uuid, $answer['answer']) : '';
                }
                $formAnswers[] = [
                    "field_id" => $answer['field_id'],
                    "answer"   => $answer['answer'],
                ];
            }

            $formSubmission->answers()->createMany($formAnswers);
        }
    }

    public function down(): void
    {
    }
}
