import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { NextRequest, NextResponse } from 'next/server';
import { getBootstrapSetupStatus } from '@/features/setup/server/setup-bootstrap.service';
import { getInstallationProfileBundle } from '@/features/setup/plugins/plugin-registry';
import { AuthError, requireSystemRole } from '@/lib/auth/session';

interface SetupTemplateMetadata {
  version: string;
  generatedFrom: string;
  templates: Array<{
    file: string;
    seedType: string;
    importOrder: number;
    supported: boolean;
    requiredColumns: string[];
    description: string;
  }>;
}

export async function GET(request: NextRequest) {
  try {
    const bootstrapStatus = await getBootstrapSetupStatus();

    if (bootstrapStatus.initialized) {
      await requireSystemRole('super_admin');
    }

    const profileId = request.nextUrl.searchParams.get('profile') ?? 'crm_demo';
    const metadataPath = path.join(process.cwd(), 'setup', 'templates', 'templates.json');
    const metadata = JSON.parse(await readFile(metadataPath, 'utf8')) as SetupTemplateMetadata;
    const profileBundle = getInstallationProfileBundle(profileId);
    const pluginTemplateByFile = new Map(
      profileBundle.templates.map((template) => [template.file, template])
    );
    const selectedTemplateFiles = new Set(profileBundle.selectedProfile?.requiredTemplates ?? []);

    const templates = metadata.templates.map((template) => {
      const pluginTemplate = pluginTemplateByFile.get(template.file);
      return {
        ...template,
        plugin: pluginTemplate?.plugin ?? (template.importOrder < 30 ? 'foundation' : 'crm'),
        profiles: pluginTemplate?.profiles ?? ['crm_demo', 'production', 'custom'],
        visible: selectedTemplateFiles.size === 0 || selectedTemplateFiles.has(template.file)
      };
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      version: metadata.version,
      generatedFrom: metadata.generatedFrom,
      profile: profileBundle.selectedProfile,
      plugins: profileBundle.plugins,
      templates
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load setup templates' }, { status: 500 });
  }
}
