const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs'); // Import fs
const db = require('./models');
const errorMiddleware = require('./middleware/errorMiddleware');
// Import seeder logic directly to run it programmatically
const seeder = require('./seeders/20251128110234-demo-data');

const app = express();

// Ensure uploads directory exists
const uploadDir = path.join(__dirname, 'uploads/cvs');
if (!fs.existsSync(uploadDir)){
    fs.mkdirSync(uploadDir, { recursive: true });
}

// Middleware
app.use(cors({
    origin: ['https://bizhire.biztech.ae', 'http://localhost:3000'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve uploaded files statically
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API Routes
app.use('/api/auth', require('./routes/auth.routes'));
app.use('/api/profiles', require('./routes/profile.routes'));
app.use('/api/jobs', require('./routes/job.routes'));
app.use('/api/applications', require('./routes/application.routes'));
app.use('/api/admin', require('./routes/admin.routes'));

// Health Check Endpoint
app.get('/', (req, res) => {
    res.send('Biz Hire API is running...');
});

// Centralized Error Handling
app.use(errorMiddleware);

// Sync database
const RESET_DB = false; // Keep false to preserve data now

db.sequelize.sync({ force: RESET_DB }).then(async () => {
    console.log("Database synced.");
    if (RESET_DB) {
        console.log("Seeding data...");
        try {
            await seeder.up(db.sequelize.getQueryInterface(), db.Sequelize);
            console.log("Data seeded successfully.");
        } catch (seedError) {
            console.error("Seeding failed:", seedError);
        }
    }
}).catch(err => {
    console.error("Failed to sync db: " + err.message);
});

module.exports = app;