<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /** Path helper */
    private function sql(string $file): string
    {
        return base_path("vendor/sabre/dav/examples/sql/{$file}");
    }

    private function prefix(): string
    {
        $driver = DB::connection()->getDriverName();

        return match ($driver) {
            'sqlite' => 'sqlite',
            'pgsql'  => 'pgsql',
            default  => 'mysql',
        };
    }

    public function up(): void
    {
        $prefix = $this->prefix();
        Schema::disableForeignKeyConstraints();

        // Principals (users & groups)
        DB::unprepared(File::get($this->sql("{$prefix}.principals.sql")));

        // CalDAV calendars + objects
        DB::unprepared(File::get($this->sql("{$prefix}.calendars.sql")));

        // CardDAV address books + cards
        DB::unprepared(File::get($this->sql("{$prefix}.addressbooks.sql")));

        Schema::enableForeignKeyConstraints();
    }

    public function down(): void
    {
        $this->prefix();
        Schema::disableForeignKeyConstraints();

        // Drop in reverse dependency order
        DB::statement('DROP TABLE IF EXISTS
            cards_changes,
            addressbooks_changes,
            cards,
            addressbooks,
            schedulingobjects,
            calendarchanges,
            calendarobjects,
            calendarinstances,
            calendars,
            groupmembers
        ');

        Schema::enableForeignKeyConstraints();
    }
};
