const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const db = require('./config/database');
const UserRoute = require('./routes/UserRoute');
const AccountRoute = require('./routes/AccountRoute');
const CategoryRoute = require('./routes/CategoryRoute');
const TransactionRoute = require('./routes/TransactionRoute');
const SavingGoalRoute = require('./routes/SavingGoalRoute');
const SubAccountRoute = require('./routes/SubAccountRoute');
const TransferRoute = require('./routes/TransferRoute');

dotenv.config();
const app = express();

app.use(cors());
app.use(express.json());
app.use(UserRoute);
app.use(AccountRoute);
app.use(CategoryRoute);
app.use(TransactionRoute);
app.use(SavingGoalRoute);
app.use(SubAccountRoute);
app.use(TransferRoute)

require('./models/CategoryModel');
require('./models/AccountModel');
require('./models/UserModel');
require('./models/TransactionModel')
require('./models/SavingGoalModel');
require('./models/SavingTransactionModel');
require('./models/SubAccountModel');
require('./models/TransferModel');

const startServer = async () => {
    try {
        await db.authenticate();
        console.log('Berhasil Terhubung dengan Database MySQL!');

        await db.sync();
        console.log('Database Synced (Tabel berhasil dibuat)!');
        
        app.listen(process.env.PORT, ()=> {
            console.log(`Server berjalan di port ${process.env.PORT}`)
        });
    } catch (error){
        console.error('Gagal terkoneksi ke database:', error);
    }
    
};

startServer();