<?php

declare(strict_types=1);

final class MicFormService
{
    public function __construct(
        private readonly MicFormRepository $forms,
        private readonly MicFormSubmissionRepository $submissions,
    ) {
    }

    public function list(): array
    {
        $forms = [];
        foreach ($this->forms->listAll() as $form) {
            $form['referencesCount'] = count($this->forms->findReferencingPages((string) $form['id']));
            $form['submissionsCount'] = $this->submissions->countForForm((string) $form['id']);
            $forms[] = $form;
        }
        return ['forms' => $forms];
    }

    public function read(string $formId): array
    {
        $form = $this->forms->findById($formId);
        if ($form === null) {
            throw new InvalidArgumentException('Form not found.');
        }
        return ['form' => $form];
    }

    public function create(array $input, MyronActionCallerContext $caller): array
    {
        $input['created_by'] = $caller->callerId;
        $input['updated_by'] = $caller->callerId;
        return ['form' => $this->forms->create($input)];
    }

    public function update(string $formId, array $input, MyronActionCallerContext $caller): array
    {
        $input['updated_by'] = $caller->callerId;
        return ['form' => $this->forms->update($formId, $input)];
    }

    public function delete(string $formId): array
    {
        return ['deleted' => $this->forms->delete($formId)];
    }

    public function duplicate(string $formId, MyronActionCallerContext $caller): array
    {
        $form = $this->forms->findById($formId);
        if ($form === null) {
            throw new InvalidArgumentException('Form not found.');
        }
        unset($form['id'], $form['created_at'], $form['updated_at'], $form['honeypot_field_name']);
        $form['name'] = (string) ($form['name'] ?? 'Form') . ' (copy)';
        return $this->create($form, $caller);
    }

    public function listSubmissions(string $formId, int $limit = 50, int $offset = 0): array
    {
        return ['submissions' => $this->submissions->listForForm($formId, $limit, $offset)];
    }

    public function readSubmission(string $submissionId): array
    {
        $submission = $this->submissions->findById($submissionId);
        if ($submission === null) {
            throw new InvalidArgumentException('Submission not found.');
        }
        return ['submission' => $submission];
    }

    public function deleteSubmission(string $submissionId): array
    {
        return ['deleted' => $this->submissions->delete($submissionId)];
    }
}
