<?php
declare(strict_types=1);

namespace App\Repositories;

use App\Json\FileStore;

class JsonArtistRepository implements ArtistRepository
{
    public function __construct(private FileStore $store) {}

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

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

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

    public function all(bool $activeOnly = false): array
    {
        $list = $this->list();
        if ($activeOnly) {
            $list = array_values(array_filter($list, fn($a) => (bool)($a['is_active'] ?? true)));
        }
        usort($list, fn($a, $b) => (int)($a['sort_index'] ?? 0) - (int)($b['sort_index'] ?? 0));
        return $list;
    }

    public function save(array $artist): array
    {
        $now = now_iso();
        $artist['updated_at'] = $now;
        if (empty($artist['id'])) {
            $artist['id'] = uuid();
            $artist['created_at'] = $now;
        }
        if (empty($artist['slug']) && !empty($artist['display_name'])) {
            $artist['slug'] = self::slugify($artist['display_name']);
        }
        $this->store->transaction(function ($d) use (&$artist) {
            $list = $d['artists'] ?? [];
            $found = false;
            foreach ($list as $i => $a) {
                if (($a['id'] ?? null) === $artist['id']) {
                    $list[$i] = array_merge($a, $artist);
                    $artist = $list[$i];
                    $found = true;
                    break;
                }
            }
            if (!$found) $list[] = $artist;
            $d['artists'] = $list;
            return $d;
        });
        return $artist;
    }

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

    public static function slugify(string $text): string
    {
        $text = strtolower(trim($text));
        $text = preg_replace('/[^a-z0-9]+/', '-', $text);
        return trim($text, '-') ?: 'artist';
    }
}
