import type { ApplicationService } from '@adonisjs/core/types';
import { configProvider } from '@adonisjs/core';
import { RuntimeException } from '@poppinss/utils';
import InertiaMiddleware from '@adonisjs/inertia/inertia_middleware';
import { ResolvedConfig } from '@adonisjs/inertia/types';

export default class InertiaProvider {
    constructor(protected app: ApplicationService) {}

    /**
     * Register bindings to the container
     */
    async register() {
        this.app.container.singleton(InertiaMiddleware, async () => {
            const inertiaConfigProvider = this.app.config.get('inertia');
            const config: ResolvedConfig | null = await configProvider.resolve(this.app, inertiaConfigProvider);
            // const vite = await this.app.container.make("vite");
            if (!config) {
                throw new RuntimeException('Invalid "config/inertia.ts" file. Make sure you are using the "defineConfig" method');
            }
            // return new InertiaMiddleware(config, vite);
            return new InertiaMiddleware(config);
        });
        await this.registerEdgePlugin();
    }

    /**
     * The container bindings have booted
     */
    async boot() {}

    /**
     * The application has been booted
     */
    async start() {}

    /**
     * The process has been started
     */
    async ready() {}

    /**
     * Preparing to shutdown the app
     */
    async shutdown() {}

    protected async registerEdgePlugin(): Promise<void> {
        if (!this.app.usingEdgeJS) return;
        const edgeExports = await import('edge.js');
        const { edgePluginInertia } = await import('@adonisjs/inertia/plugins/edge');
        edgeExports.default.use(edgePluginInertia());
    }
}
