import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import 'dotenv/config';
import sequelize from './config/database.js';
import passport from './config/passport.js';
import { errorHandler, notFoundHandler } from './middleware/errorHandler.js';

// Routes
import authRoutes from './routes/auth.js';
import projectRoutes from './routes/projects.js';
import tokenRoutes from './routes/tokens.js';
import componentRoutes from './routes/components.js';
import iconRoutes from './routes/icons.js';
import integrationRoutes from './routes/integrations.js';
import configRoutes from './routes/config.js';
import logsRoutes from './routes/logs.js';
import notificationsRoutes from './routes/notifications.js';
import mcpRoutes from './routes/mcp.js';
import teamsRoutes from './routes/teams.js';
import discoveryRoutes from './routes/discovery.js';
import figmaRoutes from './routes/figma.js';
import qaRoutes from './routes/qa.js';
import aiRoutes from './routes/ai.js';
import telemetryRoutes from './routes/telemetry.js';
import translationRoutes from './routes/translations.js';

// Admin Routes
import adminRolesRoutes from './routes/admin/roles.js';
import adminConfigRoutes from './routes/admin/config.js';

// Models
import User from './models/User.js';
import Project from './models/Project.js';
import Token from './models/Token.js';
import Component from './models/Component.js';
import Icon from './models/Icon.js';
import Integration from './models/Integration.js';
import Log from './models/Log.js';
import Team from './models/Team.js';
import TeamMember from './models/TeamMember.js';
import TeamSettings from './models/TeamSettings.js';
import Discovery from './models/Discovery.js';
import FigmaSync from './models/FigmaSync.js';
import QATest from './models/QATest.js';
import AIChat from './models/AIChat.js';
import ConfigSetting from './models/ConfigSetting.js';
import ConfigAuditLog from './models/ConfigAuditLog.js';
import TranslationDictionary from './models/TranslationDictionary.js';
import TranslationMapping from './models/TranslationMapping.js';

const app = express();
const PORT = process.env.PORT || 3001;

// Middleware
app.use(helmet());
app.use(cors({
  origin: process.env.CORS_ORIGIN?.split(',') || '*',
  credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Passport
app.use(passport.initialize());

// Health check
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'success',
    code: 'HEALTH_OK',
    message: 'Server is healthy',
    data: { timestamp: new Date().toISOString() }
  });
});

// API Routes
app.use('/api/auth', authRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/tokens', tokenRoutes);
app.use('/api/components', componentRoutes);
app.use('/api/icons', iconRoutes);
app.use('/api/integrations', integrationRoutes);
app.use('/api/config', configRoutes);
app.use('/api/logs', logsRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/mcp', mcpRoutes);
app.use('/api/teams', teamsRoutes);
app.use('/api/discovery', discoveryRoutes);
app.use('/api/figma', figmaRoutes);
app.use('/api/qa', qaRoutes);
app.use('/api/test', qaRoutes);
app.use('/api/claude', aiRoutes);
app.use('/api/ai', aiRoutes);
app.use('/api/dss', aiRoutes);
app.use('/api/navigation', aiRoutes);
app.use('/api/system', aiRoutes);
app.use('/api/assets', aiRoutes);
app.use('/api/telemetry', telemetryRoutes);
app.use('/api/translations', translationRoutes);

// Admin Routes
app.use('/api/admin/roles', adminRolesRoutes);
app.use('/api/admin/config', adminConfigRoutes);

// Error handling
app.use(notFoundHandler);
app.use(errorHandler);

// Database relationships
User.hasMany(Project, { foreignKey: 'userId' });
Project.belongsTo(User, { foreignKey: 'userId' });

Project.hasMany(Token, { foreignKey: 'projectId' });
Token.belongsTo(Project, { foreignKey: 'projectId' });

Project.hasMany(Component, { foreignKey: 'projectId' });
Component.belongsTo(Project, { foreignKey: 'projectId' });

Project.hasMany(Icon, { foreignKey: 'projectId' });
Icon.belongsTo(Project, { foreignKey: 'projectId' });

Project.hasMany(Integration, { foreignKey: 'projectId' });
Integration.belongsTo(Project, { foreignKey: 'projectId' });

User.hasMany(Log, { foreignKey: 'userId' });
Log.belongsTo(User, { foreignKey: 'userId' });

// Team relationships (Phase 3)
User.hasMany(Team, { foreignKey: 'ownerId' });
Team.belongsTo(User, { foreignKey: 'ownerId' });

Team.hasMany(TeamMember, { foreignKey: 'teamId' });
TeamMember.belongsTo(Team, { foreignKey: 'teamId' });

User.hasMany(TeamMember, { foreignKey: 'userId' });
TeamMember.belongsTo(User, { foreignKey: 'userId' });

Team.hasOne(TeamSettings, { foreignKey: 'teamId' });
TeamSettings.belongsTo(Team, { foreignKey: 'teamId' });

// Discovery relationships (Phase 4)
User.hasMany(Discovery, { foreignKey: 'userId' });
Discovery.belongsTo(User, { foreignKey: 'userId' });

Project.hasMany(Discovery, { foreignKey: 'projectId' });
Discovery.belongsTo(Project, { foreignKey: 'projectId' });

// FigmaSync relationships (Phase 5A)
User.hasMany(FigmaSync, { foreignKey: 'userId' });
FigmaSync.belongsTo(User, { foreignKey: 'userId' });

Project.hasMany(FigmaSync, { foreignKey: 'projectId' });
FigmaSync.belongsTo(Project, { foreignKey: 'projectId' });

// QATest relationships (Phase 5B)
User.hasMany(QATest, { foreignKey: 'userId' });
QATest.belongsTo(User, { foreignKey: 'userId' });

Project.hasMany(QATest, { foreignKey: 'projectId' });
QATest.belongsTo(Project, { foreignKey: 'projectId' });

// AIChat relationships (Phase 5C)
User.hasMany(AIChat, { foreignKey: 'userId' });
AIChat.belongsTo(User, { foreignKey: 'userId' });

Project.hasMany(AIChat, { foreignKey: 'projectId' });
AIChat.belongsTo(Project, { foreignKey: 'projectId' });

// Config relationships (Track 2)
ConfigSetting.hasMany(ConfigAuditLog, { foreignKey: 'configId' });
ConfigAuditLog.belongsTo(ConfigSetting, { foreignKey: 'configId' });

User.hasMany(ConfigAuditLog, { foreignKey: 'actorId' });
ConfigAuditLog.belongsTo(User, { foreignKey: 'actorId' });

// Translation Dictionary relationships (Phase 2B)
Project.hasMany(TranslationDictionary, { foreignKey: 'projectId' });
TranslationDictionary.belongsTo(Project, { foreignKey: 'projectId' });

User.hasMany(TranslationDictionary, { foreignKey: 'createdBy' });
TranslationDictionary.belongsTo(User, { foreignKey: 'createdBy' });

TranslationDictionary.hasMany(TranslationMapping, { foreignKey: 'dictionaryId', onDelete: 'CASCADE' });
TranslationMapping.belongsTo(TranslationDictionary, { foreignKey: 'dictionaryId' });

// Initialize database and start server
const startServer = async () => {
  try {
    await sequelize.authenticate();
    console.log('[Server] Database connection established');

    await sequelize.sync({ alter: process.env.NODE_ENV === 'development' });
    console.log('[Server] Database models synchronized');

    app.listen(PORT, () => {
      console.log(`[Server] API running on http://localhost:${PORT}`);
      console.log(`[Server] Environment: ${process.env.NODE_ENV || 'development'}`);
    });
  } catch (error) {
    console.error('[Server] Failed to start:', error);
    process.exit(1);
  }
};

startServer();

export default app;
