import { poster } from './poster.js';
import { start as startProfiler } from '@google-cloud/profiler'; // Renamed import for clarity
import cors from 'cors';
import express from 'express';

// --- Configuration ---
const PORT = process.env.PORT || 3000;
// Enable profiler, e.g., only in production environments
const PROFILER_ENABLED = process.env.ENABLE_PROFILER === 'true' || process.env.NODE_ENV === 'production';
const SERVICE_NAME = 'movie_posters';
const SERVICE_VERSION = '1.0.0'; // Consider reading from package.json

// --- Application Setup ---
const app = express();

// --- Google Cloud Profiler Setup ---
if (PROFILER_ENABLED) {
    startProfiler({
        projectId: process.env.PROJECT_ID, // Ensure PROJECT_ID is set in the environment
        serviceContext: {
            service: SERVICE_NAME,
            version: SERVICE_VERSION,
        },
    }).then(() => {
        console.log(`Google Cloud Profiler started for service ${SERVICE_NAME} v${SERVICE_VERSION}.`);
    }).catch(err => {
        // Log the error but don't prevent the app from starting
        console.error('Failed to start Google Cloud Profiler:', err);
    });
} else {
    console.log('Google Cloud Profiler is disabled.');
}

// --- Core Middleware ---
app.use(cors()); // Enable Cross-Origin Resource Sharing for all origins
app.use(express.json()); // Parse incoming JSON request bodies

// --- Specific Error Handling Middleware ---
// Handles JSON parsing errors specifically, providing a clearer error message.
app.use((err, req, res, next) => {
    // Check if the error is a syntax error thrown by express.json()
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error('Bad JSON format received:', err.message);
        return res.status(400).send({ error: 'Invalid JSON format in request body.' });
    }
    // Pass other errors down the middleware chain
    next(err);
});

app.use('/poster', poster.router);

// --- Routes ---

// Root GET endpoint: Provides basic API status information.
app.get("/", (req, res) => {
    res.status(200).send({
        status: 'API is running.',
        message: 'Use the POST /poster endpoint with a JSON body to generate posters.',
        service: SERVICE_NAME,
        version: SERVICE_VERSION
    });
});

// --- Generic Error Handler ---
// Catches any errors passed via `next(err)` from preceding middleware or routes.
// This should be the last middleware added.
app.use((err, req, res, next) => {
    console.error("Unhandled application error:", err);
    // Ensure response is sent only once
    if (!res.headersSent) {
        res.status(500).send({ error: 'An internal server error occurred.' });
    }
});

// --- Server Start ---
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
    console.log(`Access the API at http://localhost:${PORT}`);
    if (PROFILER_ENABLED) {
        console.log(`Google Cloud Profiler is active for project: ${process.env.PROJECT_ID || 'Not Specified'}`);
    }
});
