<?php

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

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

    public function up(): void
    {
        // Disable FK checks for smooth batch execution
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');

        // Principals (users & groups)
        DB::unprepared(File::get($this->sql('mysql.principals.sql')));

        // CalDAV calendars + objects
        DB::unprepared(File::get($this->sql('mysql.calendars.sql')));

        // CardDAV address books + cards
        DB::unprepared(File::get($this->sql('mysql.addressbooks.sql')));

        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

    public function down(): void
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');

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

        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }
};
