import { NextResponse } from 'next/server';
import { validateApiKey, getProjectContent, getProjectApiKey, deleteProject, projectExists } from '@/lib/storage/blob';
/**
 * GET /api/projects/[slug]
 * Get detailed project information
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 */ export async function GET(request, { params }) {
    try {
        const { slug } = await params;
        // Validate API key
        const authHeader = request.headers.get('Authorization');
        const apiKey = authHeader?.replace('Bearer ', '');
        if (!apiKey) {
            return NextResponse.json({
                error: 'API key required'
            }, {
                status: 401
            });
        }
        // Validate the API key belongs to this project
        const validatedSlug = await validateApiKey(apiKey);
        if (validatedSlug !== slug) {
            return NextResponse.json({
                error: 'API key does not match this project'
            }, {
                status: 403
            });
        }
        // Get project details
        const content = await getProjectContent(slug);
        const keyData = await getProjectApiKey(slug);
        if (!content) {
            return NextResponse.json({
                error: 'Project not found'
            }, {
                status: 404
            });
        }
        // Parse docs.json
        let docsConfig = {};
        try {
            docsConfig = JSON.parse(content.docsJson);
        } catch  {
        // Ignore parse errors
        }
        // Build file list (without content for security/size)
        const files = content.files.map((f)=>({
                path: f.path,
                size: f.content.length
            }));
        return NextResponse.json({
            slug: content.slug,
            name: content.name,
            url: `https://${slug}.devdoc.sh`,
            createdAt: content.createdAt,
            updatedAt: content.updatedAt,
            lastDeployedAt: keyData?.lastUsedAt || content.updatedAt,
            filesCount: content.files.length,
            totalSize: content.files.reduce((sum, f)=>sum + f.content.length, 0),
            files,
            config: {
                name: docsConfig.name,
                favicon: docsConfig.favicon,
                navigation: docsConfig.navigation ? 'configured' : 'default'
            }
        });
    } catch (error) {
        console.error('[Projects API] GET Error:', error);
        return NextResponse.json({
            error: 'Internal server error'
        }, {
            status: 500
        });
    }
}
/**
 * DELETE /api/projects/[slug]
 * Delete a project and all its content
 * 
 * Headers:
 *   Authorization: Bearer <api_key>
 */ export async function DELETE(request, { params }) {
    try {
        const { slug } = await params;
        // Validate API key
        const authHeader = request.headers.get('Authorization');
        const apiKey = authHeader?.replace('Bearer ', '');
        if (!apiKey) {
            return NextResponse.json({
                error: 'API key required'
            }, {
                status: 401
            });
        }
        // Validate the API key belongs to this project
        const validatedSlug = await validateApiKey(apiKey);
        if (validatedSlug !== slug) {
            return NextResponse.json({
                error: 'API key does not match this project'
            }, {
                status: 403
            });
        }
        // Check project exists
        const exists = await projectExists(slug);
        if (!exists) {
            return NextResponse.json({
                error: 'Project not found'
            }, {
                status: 404
            });
        }
        // Delete the project
        await deleteProject(slug);
        return NextResponse.json({
            success: true,
            message: `Project ${slug} has been deleted`
        });
    } catch (error) {
        console.error('[Projects API] DELETE Error:', error);
        return NextResponse.json({
            error: 'Internal server error'
        }, {
            status: 500
        });
    }
}
