<?php
declare(strict_types=1);

namespace App\Repositories;

use App\Json\FileStore;

class JsonIntakeFormRepository implements IntakeFormRepository
{
    public function __construct(private FileStore $store) {}

    private function list(): array
    {
        $d = $this->store->read();
        return $d['intake_forms'] ?? [];
    }

    public function find(string $id): ?array
    {
        foreach ($this->list() as $f) if (($f['id'] ?? null) === $id) return $f;
        return null;
    }

    public function findByResumeToken(string $token): ?array
    {
        if ($token === '') return null;
        foreach ($this->list() as $f) if (($f['resume_token'] ?? null) === $token) return $f;
        return null;
    }

    public function forCustomer(string $customerId): array
    {
        $list = array_values(array_filter($this->list(), fn($f) => ($f['customer_id'] ?? '') === $customerId));
        usort($list, fn($a, $b) => strcmp((string)($b['created_at'] ?? ''), (string)($a['created_at'] ?? '')));
        return $list;
    }

    public function all(array $filters = []): array
    {
        $list = $this->list();
        if (!empty($filters['status'])) {
            $list = array_values(array_filter($list, fn($f) => ($f['status'] ?? '') === $filters['status']));
        }
        usort($list, fn($a, $b) => strcmp((string)($b['updated_at'] ?? $b['created_at'] ?? ''), (string)($a['updated_at'] ?? $a['created_at'] ?? '')));
        return $list;
    }

    public function save(array $form): array
    {
        $now = now_iso();
        $form['updated_at'] = $now;
        if (empty($form['id'])) {
            $form['id'] = uuid();
            $form['created_at'] = $now;
            $form['status'] = $form['status'] ?? 'DRAFT';
            $form['resume_token'] = $form['resume_token'] ?? uuid();
        }
        $this->store->transaction(function ($d) use (&$form) {
            $list = $d['intake_forms'] ?? [];
            $found = false;
            foreach ($list as $i => $f) {
                if (($f['id'] ?? null) === $form['id']) {
                    $list[$i] = array_merge($f, $form);
                    $form = $list[$i];
                    $found = true;
                    break;
                }
            }
            if (!$found) $list[] = $form;
            $d['intake_forms'] = $list;
            return $d;
        });
        return $form;
    }

    public function delete(string $id): void
    {
        $this->store->transaction(function ($d) use ($id) {
            $d['intake_forms'] = array_values(array_filter($d['intake_forms'] ?? [], fn($f) => ($f['id'] ?? null) !== $id));
            return $d;
        });
    }
}
