import express from 'express';
import cors from 'cors';
import projectRoutes from './routes/projectRoutes.js';
import partRoutes from './routes/partRoutes.js';
import paintingSchemeRoutes from './routes/paintingSchemeRoutes.js';
import applicationRecordRoutes from './routes/applicationRecordRoutes.js';
import inspectionRoutes from './routes/inspectionRoutes.js';
import analysisRoutes from './routes/analysisRoutes.js';
import dataSheetRoutes from './routes/dataSheetRoutes.js';
import yieldStudyRoutes from './routes/yieldStudyRoutes.js';
import userRoutes from './routes/userRoutes.js';
import systemSettingsRoutes from './routes/systemSettingsRoutes.js';
import geometryTypeRoutes from './routes/geometryTypeRoutes.js';

import stockRoutes from './routes/stockRoutes.js';
import notificationRoutes from './routes/notificationRoutes.js';
import instrumentRoutes from './routes/instrumentRoutes.js';
import messageRoutes from './routes/messageRoutes.js';
import backupRoutes from './routes/backupRoutes.js';
import path from 'path';

const app = express();

app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'x-organization-id']
}));
app.use(express.json());
import { extractUser } from './middleware/authMiddleware.js';
app.use(extractUser);

// Static Uploads
import fs from 'fs';
const uploadsPath = path.join(process.cwd(), 'uploads');

if (!fs.existsSync(uploadsPath)) {
    fs.mkdirSync(uploadsPath, { recursive: true });
}

app.use('/uploads', express.static(uploadsPath));

// Serve frontend static files
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));

// 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/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.use('/api/messages', messageRoutes);
app.use('/api/backup', backupRoutes);

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

// SPA fallback - must be last
app.use((req, res, next) => {
    res.sendFile(path.join(distPath, 'index.html'));
});

export default app;
