<?php
declare(strict_types=1);

namespace App\Repositories;

use App\Json\FileStore;

class JsonScheduleRepository implements ScheduleRepository
{
    public function __construct(private FileStore $store) {}

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

    public function weeklyForArtist(string $artistId): array
    {
        $d = $this->read();
        return array_values(array_filter($d['weekly'], fn($r) => ($r['artist_id'] ?? null) === $artistId));
    }

    public function exceptionsForArtistOnDate(string $artistId, string $date): array
    {
        $d = $this->read();
        return array_values(array_filter($d['exceptions'], fn($r) => ($r['artist_id'] ?? null) === $artistId && ($r['date'] ?? null) === $date));
    }

    public function exceptionsForArtistInRange(string $artistId, string $startDate, string $endDate): array
    {
        $d = $this->read();
        return array_values(array_filter($d['exceptions'], function ($r) use ($artistId, $startDate, $endDate) {
            if (($r['artist_id'] ?? null) !== $artistId) return false;
            $d = $r['date'] ?? '';
            return $d >= $startDate && $d <= $endDate;
        }));
    }

    public function replaceWeekly(string $artistId, array $rows): void
    {
        $this->store->transaction(function ($d) use ($artistId, $rows) {
            $weekly = array_values(array_filter($d['weekly'] ?? [], fn($r) => ($r['artist_id'] ?? null) !== $artistId));
            foreach ($rows as $row) {
                $row['id'] = $row['id'] ?? uuid();
                $row['artist_id'] = $artistId;
                $weekly[] = $row;
            }
            $d['weekly'] = $weekly;
            $d['exceptions'] = $d['exceptions'] ?? [];
            return $d;
        });
    }

    public function addException(array $ex): array
    {
        if (empty($ex['id'])) $ex['id'] = uuid();
        $ex['created_at'] = now_iso();
        $this->store->transaction(function ($d) use ($ex) {
            $d['weekly'] = $d['weekly'] ?? [];
            $d['exceptions'] = $d['exceptions'] ?? [];
            $d['exceptions'][] = $ex;
            return $d;
        });
        return $ex;
    }

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