<?php

declare(strict_types=1);
final class Asm3ResetService
{
    public static function clear(PDO $db): array
    {
        $before = [
            'animals' => (int) $db->query('SELECT COUNT(*) FROM animals')->fetchColumn(),
            'contacts' => (int) $db->query('SELECT COUNT(*) FROM directory_contacts')->fetchColumn(),
        ];
        $tables = [
            'agenda_volunteers',
            'agenda_items',
            'prescription_treatments',
            'lab_results',
            'medical_prescriptions',
            'lab_reports',
            'treatment_administrations',
            'care_round_observations',
            'animal_photos',
            'medical_photos',
            'animal_health_conditions',
            'vaccinations',
            'treatments',
            'medical_notes',
            'measurements',
            'animal_placements',
            'adoptions',
            'animal_movements',
            'animal_deaths',
            'animal_location_history',
            'animal_history',
            'litter_kittens',
            'litters',
            'bonded_group_members',
            'bonded_groups',
            'care_rounds',
            'icad_cache',
            'asm3_import_links',
            'asm3_import_runs',
            'directory_contact_roles',
            'animals',
            'directory_contacts',
        ];
        foreach ($tables as $table) {
            $db->exec('DELETE FROM ' . $table);
        }
        return $before;
    }
    public static function clearMedia(): void
    {
        foreach (
            [dirname(__DIR__, 2) . '/public/media/animals', dirname(__DIR__, 2) . '/data/medical-documents']
            as $root
        ) {
            if (!is_dir($root)) {
                continue;
            }
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::CHILD_FIRST,
            );
            foreach ($iterator as $file) {
                $path = $file->getPathname();
                if ($file->isLink()) {
                    unlink($path);
                } elseif ($file->isDir()) {
                    rmdir($path);
                } else {
                    unlink($path);
                }
            }
        }
    }
}
