import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';

import authRoutes from './routes/auth.js';
import usersRoutes from './routes/users.js';
import vehiclesRoutes from './routes/vehicles.js';
import servicesRoutes from './routes/services.js';
import bookingsRoutes from './routes/bookings.js';
import jobCardsRoutes from './routes/jobCards.js';
import tasksRoutes from './routes/tasks.js';
import adminRoutes from './routes/admin.js';
import chatRoutes from './routes/chat.js';
import attendanceRoutes from './routes/attendance.js';
import externalRoutes from './routes/external.js';
import { sendError } from './util/httpError.js';
import { sequelize } from './models/index.js';

dotenv.config();

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const port = Number(process.env.PORT || 3000);

app.use(helmet({ crossOriginResourcePolicy: { policy: 'cross-origin' } }));
app.use(cors({ origin: true, credentials: true }));
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

app.get('/api/health', (_req, res) => res.json({ ok: true }));

app.use('/api/auth', authRoutes);
app.use('/api/users', usersRoutes);
app.use('/api/vehicles', vehiclesRoutes);
app.use('/api/services', servicesRoutes);
app.use('/api/bookings', bookingsRoutes);
app.use('/api/job-cards', jobCardsRoutes);
app.use('/api/tasks', tasksRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/chat', chatRoutes);
app.use('/api/attendance', attendanceRoutes);
app.use('/api/external', externalRoutes);

app.use((err, _req, res, _next) => {
  console.error(err);
  return sendError(
    res,
    500,
    'INTERNAL_ERROR',
    process.env.NODE_ENV === 'production' ? 'Server error' : String(err.message)
  );
});

app.use((_req, res) => {
  return sendError(res, 404, 'NOT_FOUND', 'Route not found');
});

export default app;

async function start() {
  try {
    await sequelize.authenticate();
    await sequelize.sync();

    // Seed default services if none exist
    const { Service } = await import('./models/index.js');
    const count = await Service.count();
    if (count === 0) {
      console.log('Seeding default services...');
      await Service.bulkCreate([
        { name: 'Full Body Paint', price: 25000 },
        { name: 'Dent Removal (Per Panel)', price: 1500 },
        { name: 'Premium Foam Wash', price: 800 },
        { name: 'Interior Deep Cleaning', price: 2500 },
        { name: 'Ceramic Coating', price: 15000 },
        { name: 'Underbody Rust Coating', price: 3500 },
        { name: 'Bumper Scuff Repair', price: 2000 },
        { name: 'Alloy Wheel Painting', price: 4000 },
      ]);
    }

    app.listen(port, () => {
      console.log(`API listening on http://localhost:${port}`);
    });
  } catch (err) {
    console.error('Failed to start server:', err);
  }
}

if (process.env.AUTO_START !== 'false') {
  start();
}

process.on('unhandledRejection', (reason) => {
  console.error('unhandledRejection', reason);
});
