'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
require('dotenv').config();

const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '../config/config.js'))[env];
const db = {};

const logFilePath = path.join(__dirname, '..', 'sequelize.log');
// const logStream = fs.createWriteStream(logFilePath, { flags: 'a' });

let sequelize;
if (config.use_env_variable) {
	sequelize = new Sequelize(process.env[config.use_env_variable], {
		...config,
		// logging: (msg) => logStream.write(msg + '\n'),
	});
} else {
	sequelize = new Sequelize(config.database, config.username, config.password, {
		...config,
		// logging: (msg) => logStream.write(msg + '\n'),
	});
}

fs.readdirSync(__dirname)
	.filter((file) => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')
	.forEach((file) => {
		const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
		db[model.name] = model;
	});

Object.keys(db).forEach((modelName) => {
	if (db[modelName].associate) {
		db[modelName].associate(db);
	}
});

module.exports = {
	sequelize,
	Sequelize,
	Members: db.Members,
	LinkedTickets: db.LinkedTickets,
	Tickets: db.Tickets,
	ConventionUsers: db.ConventionUsers,
	Drivers: db.Drivers,
	PasswordResetTokens: db.PasswordResetTokens,
	WorldConTickets: db.WorldConTickets,
	Posts: db.Posts,
	PostImages: db.PostImages,
	PostLikes: db.PostLikes,
	PostComments: db.PostComments,
	CommentLikes: db.CommentLikes,
	PostTags: db.PostTags,
	Activities: db.Activities,
	ActivityImages: db.ActivityImages,
	ActivityLikes: db.ActivityLikes,
	ActivityBookings: db.ActivityBookings,
	ActivityReviews: db.ActivityReviews,
	ActivityReviewImages: db.ActivityReviewImages,
	ActivityItineraries: db.ActivityItineraries,
	Events: db.Events,
	EventRegistrations: db.EventRegistrations,
	Products: db.Products,
	ProductDetails: db.ProductDetails,
	ProductImages: db.ProductImages,
	ProductCarts: db.ProductCarts,
	ProductPurchases: db.ProductPurchases,
	ProductPurchaseItems: db.ProductPurchaseItems,
	Hotels: db.Hotels,
	HotelImages: db.HotelImages,
	HotelRooms: db.HotelRooms,
	HotelRoomImages: db.HotelRoomImages,
	HotelBookings: db.HotelBookings,
	HotelReviews: db.HotelReviews,
	HotelReviewImages: db.HotelReviewImages,
	Restaurants: db.Restaurants,
	RestaurantImages: db.RestaurantImages,
	RestaurantSaves: db.RestaurantSaves,
	RestaurantReviews: db.RestaurantReviews,
	RestaurantReviewImages: db.RestaurantReviewImages,
	RestaurantHours: db.RestaurantHours,
	CocTeam: db.CocTeam,
	Faqs: db.Faqs,
	BusStops: db.BusStops,
	BusSchedules: db.BusSchedules,
	Concerns: db.Concerns,
	ConcernMessages: db.ConcernMessages,
	Notifications: db.Notifications,
	RefreshTokens: db.RefreshTokens,
	Rides: db.Rides,
	Routes: db.Routes,
	RouteSchedules: db.RouteSchedules,
	EventAttendies: db.EventAttendies,
};
