import express from 'express';
import cors from 'cors';
import projectRoutes from '../src/server/routes/projectRoutes.js';
import partRoutes from '../src/server/routes/partRoutes.js';
import paintingSchemeRoutes from '../src/server/routes/paintingSchemeRoutes.js';
import applicationRecordRoutes from '../src/server/routes/applicationRecordRoutes.js';
import inspectionRoutes from '../src/server/routes/inspectionRoutes.js';
import analysisRoutes from '../src/server/routes/analysisRoutes.js';
import dataSheetRoutes from '../src/server/routes/dataSheetRoutes.js';
import yieldStudyRoutes from '../src/server/routes/yieldStudyRoutes.js';
import userRoutes from '../src/server/routes/userRoutes.js';
import systemSettingsRoutes from '../src/server/routes/systemSettingsRoutes.js';
import geometryTypeRoutes from '../src/server/routes/geometryTypeRoutes.js';
import stockRoutes from '../src/server/routes/stockRoutes.js';
import notificationRoutes from '../src/server/routes/notificationRoutes.js';
import instrumentRoutes from '../src/server/routes/instrumentRoutes.js';
import { extractUser } from '../src/server/middleware/authMiddleware.js';
import path from 'path';

const app = express();

app.use(cors({
    origin: '*', // Be more specific in production
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'x-organization-id', 'x-organization-name']
}));
app.use(express.json());

// Global Middleware
app.use(extractUser);

// Static Uploads
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')));

// Routes
app.use('/api/users', userRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/parts', partRoutes);
app.use('/api/painting-schemes', paintingSchemeRoutes);
app.use('/api/application-records', applicationRecordRoutes);
app.use('/api/inspections', inspectionRoutes);
app.use('/api', analysisRoutes);
app.use('/api/datasheets', dataSheetRoutes);
app.use('/api/yield-studies', yieldStudyRoutes);
app.use('/api/system-settings', systemSettingsRoutes);
app.use('/api/geometry-types', geometryTypeRoutes);
app.use('/api/stock', stockRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/instruments', instrumentRoutes);

app.get('/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date() });
});

export default app;
