import { Sequelize } from 'sequelize';
import config from '../../common/config/database.js';

// Import individual model factories

// Core
import createUser from './core/User.js';
import createRole from './core/Role.js';
import createPermission from './core/Permission.js';
import createRolePermission from './core/RolePermission.js';
import createUserRole from './core/UserRole.js';
import createSystemConfiguration from './core/SystemConfiguration.js';
import createEmailTemplate from './core/EmailTemplate.js';
import createPushSubscription from './core/PushSubscription.js';
import createNotification from './core/Notification.js';
import createState from './core/State.js';
import createDistrict from './core/District.js';
import createRegion from './core/Region.js';
import createZone from './core/Zone.js';
import createLocation from './core/Location.js';

// Application
import createApplication from './application/Application.js';
import createApplicationProgress from './application/ApplicationProgress.js';
import createApplicationStatusHistory from './application/ApplicationStatusHistory.js';
import createOpportunity from './application/Opportunity.js';
import createOnboardingDocument from './application/OnboardingDocument.js';
import createDocumentVersion from './application/DocumentVersion.js';

// Dealer
import createDealer from './dealer/Dealer.js';
import createDealerCode from './dealer/DealerCode.js';
import createDealerBankDetail from './dealer/DealerBankDetail.js';
import createOutlet from './dealer/Outlet.js';

// Verification
import createInterview from './verification/Interview.js';
import createInterviewEvaluation from './verification/InterviewEvaluation.js';
import createInterviewFeedback from './verification/InterviewFeedback.js';
import createInterviewParticipant from './verification/InterviewParticipant.js';
import createQuestionnaire from './verification/Questionnaire.js';
import createQuestionnaireOption from './verification/QuestionnaireOption.js';
import createQuestionnaireQuestion from './verification/QuestionnaireQuestion.js';
import createQuestionnaireResponse from './verification/QuestionnaireResponse.js';
import createQuestionnaireScore from './verification/QuestionnaireScore.js';
import createKTMatrixScore from './verification/KTMatrixScore.js';
import createInterviewConfig from './verification/InterviewConfig.js';
import createInterviewConfigItem from './verification/InterviewConfigItem.js';
import createInterviewConfigItemOption from './verification/InterviewConfigItemOption.js';
import createAiSummary from './verification/AiSummary.js';
import createFddAssignment from './verification/FddAssignment.js';
import createFddReport from './verification/FddReport.js';

// Approval
import createLoiRequest from './approval/LoiRequest.js';
import createLoiApproval from './approval/LoiApproval.js';
import createLoiAcknowledgement from './approval/LoiAcknowledgement.js';
import createLoiDocumentGenerated from './approval/LoiDocumentGenerated.js';
import createLoaRequest from './approval/LoaRequest.js';
import createLoaApproval from './approval/LoaApproval.js';
import createLoaAcknowledgement from './approval/LoaAcknowledgement.js';
import createLoaDocumentGenerated from './approval/LoaDocumentGenerated.js';
import createSecurityDeposit from './approval/SecurityDeposit.js';

// Offboarding
import createTerminationRequest from './offboarding/termination/TerminationRequest.js';
import createTerminationAudit from './offboarding/termination/TerminationAudit.js';
import createTerminationDocument from './offboarding/termination/TerminationDocument.js';
import createTerminationHearingRecord from './offboarding/termination/TerminationHearingRecord.js';
import createTerminationScnResponse from './offboarding/termination/TerminationScnResponse.js';
import createResignation from './offboarding/resignation/Resignation.js';
import createResignationAudit from './offboarding/resignation/ResignationAudit.js';
import createResignationDocument from './offboarding/resignation/ResignationDocument.js';
import createRelocationRequest from './offboarding/relocation/RelocationRequest.js';
import createRelocationAudit from './offboarding/relocation/RelocationAudit.js';
import createRelocationDocument from './offboarding/relocation/RelocationDocument.js';
import createConstitutionalChange from './offboarding/constitutional/ConstitutionalChange.js';
import createConstitutionalAudit from './offboarding/constitutional/ConstitutionalAudit.js';
import createConstitutionalDocument from './offboarding/constitutional/ConstitutionalDocument.js';
import createExitFeedback from './offboarding/common/ExitFeedback.js';

// Financial
import createFnF from './financial/FnF.js';
import createFnFAudit from './financial/FnFAudit.js';
import createFnFLineItem from './financial/FnFLineItem.js';
import createFffClearance from './financial/FffClearance.js';
import createFinancePayment from './financial/FinancePayment.js';

// Compliance
import createEorChecklist from './compliance/EorChecklist.js';
import createEorChecklistItem from './compliance/EorChecklistItem.js';
import createSLAConfiguration from './compliance/SLAConfiguration.js';
import createSLABreach from './compliance/SLABreach.js';
import createSLAEscalationConfig from './compliance/SLAEscalationConfig.js';
import createSLAReminder from './compliance/SLAReminder.js';
import createSLATracking from './compliance/SLATracking.js';
import createSLANotificationDispatch from './compliance/SLANotificationDispatch.js';
import createWorkflowStageConfig from './compliance/WorkflowStageConfig.js';
import createStageApprovalAction from './compliance/StageApprovalAction.js';
import createStageApprovalPolicy from './compliance/StageApprovalPolicy.js';
import createDocumentStageConfig from './compliance/DocumentStageConfig.js';
import createRequestParticipant from './compliance/RequestParticipant.js';

// Activity
import createAuditLog from './activity/AuditLog.js';
import createSystemAuditLog from './activity/SystemAuditLog.js';
import createWorknote from './activity/Worknote.js';
import createWorkNoteAttachment from './activity/WorkNoteAttachment.js';
import createWorkNoteTag from './activity/WorkNoteTag.js';

// System
import createMigration from './system/Migration.js';

const env = process.env.NODE_ENV || 'development';
const dbConfig = config[env];

// Initialize Sequelize
const sequelize = new Sequelize(
    dbConfig.database!,
    dbConfig.username!,
    dbConfig.password!,
    {
        host: dbConfig.host,
        port: dbConfig.port as number,
        dialect: dbConfig.dialect as any,
        logging: dbConfig.logging,
        pool: dbConfig.pool,
        dialectOptions: dbConfig.dialectOptions
    }
);

const db: any = {};

// Initialize models
db.User = createUser(sequelize);
db.Application = createApplication(sequelize);
db.Resignation = createResignation(sequelize);
db.ConstitutionalChange = createConstitutionalChange(sequelize);
db.RelocationRequest = createRelocationRequest(sequelize);
db.Outlet = createOutlet(sequelize);
db.Worknote = createWorknote(sequelize);
db.OnboardingDocument = createOnboardingDocument(sequelize);
db.AuditLog = createAuditLog(sequelize);
db.SystemAuditLog = createSystemAuditLog(sequelize);
db.FinancePayment = createFinancePayment(sequelize);
db.RelocationDocument = createRelocationDocument(sequelize);
db.ResignationDocument = createResignationDocument(sequelize);
db.ConstitutionalDocument = createConstitutionalDocument(sequelize);
db.TerminationDocument = createTerminationDocument(sequelize);
db.FnF = createFnF(sequelize);
db.FnFLineItem = createFnFLineItem(sequelize);
db.SLAConfiguration = createSLAConfiguration(sequelize);
db.SLAReminder = createSLAReminder(sequelize);
db.SLAEscalationConfig = createSLAEscalationConfig(sequelize);
db.WorkflowStageConfig = createWorkflowStageConfig(sequelize);
db.Notification = createNotification(sequelize);
db.DocumentStageConfig = createDocumentStageConfig(sequelize);
db.District = createDistrict(sequelize);
db.Location = createLocation(sequelize);
db.Zone = createZone(sequelize);
db.Region = createRegion(sequelize);
db.State = createState(sequelize);
db.TerminationScnResponse = createTerminationScnResponse(sequelize);
db.TerminationHearingRecord = createTerminationHearingRecord(sequelize);
db.FffClearance = createFffClearance(sequelize);
db.ResignationAudit = createResignationAudit(sequelize);
db.TerminationAudit = createTerminationAudit(sequelize);
db.FnFAudit = createFnFAudit(sequelize);
db.ConstitutionalAudit = createConstitutionalAudit(sequelize);
db.RelocationAudit = createRelocationAudit(sequelize);

// Batch 1: Organizational Hierarchy & User Management
db.Role = createRole(sequelize);
db.Permission = createPermission(sequelize);
db.RolePermission = createRolePermission(sequelize);
db.UserRole = createUserRole(sequelize);

// Batch 2: Opportunity & Application Framework
db.Opportunity = createOpportunity(sequelize);
db.ApplicationStatusHistory = createApplicationStatusHistory(sequelize);
db.ApplicationProgress = createApplicationProgress(sequelize);

// Batch 3: Questionnaire & Interview Systems
db.Questionnaire = createQuestionnaire(sequelize);
db.QuestionnaireQuestion = createQuestionnaireQuestion(sequelize);
db.QuestionnaireOption = createQuestionnaireOption(sequelize);
db.QuestionnaireResponse = createQuestionnaireResponse(sequelize);
db.QuestionnaireScore = createQuestionnaireScore(sequelize);
db.Interview = createInterview(sequelize);
db.InterviewParticipant = createInterviewParticipant(sequelize);
db.InterviewEvaluation = createInterviewEvaluation(sequelize);
db.KTMatrixScore = createKTMatrixScore(sequelize);
db.InterviewFeedback = createInterviewFeedback(sequelize);
db.InterviewConfig = createInterviewConfig(sequelize);
db.InterviewConfigItem = createInterviewConfigItem(sequelize);
db.InterviewConfigItemOption = createInterviewConfigItemOption(sequelize);
db.AiSummary = createAiSummary(sequelize);

// Batch 4: Dealer Entity, Documents & Work Notes
db.Dealer = createDealer(sequelize);
db.DealerCode = createDealerCode(sequelize);
db.DealerBankDetail = createDealerBankDetail(sequelize);
db.DocumentVersion = createDocumentVersion(sequelize);
db.WorkNoteTag = createWorkNoteTag(sequelize);
db.WorkNoteAttachment = createWorkNoteAttachment(sequelize);
db.RequestParticipant = createRequestParticipant(sequelize);

// Batch 5: FDD, LOI, LOA, EOR & Security Deposit
db.FddAssignment = createFddAssignment(sequelize);
db.FddReport = createFddReport(sequelize);
db.LoiRequest = createLoiRequest(sequelize);
db.LoiApproval = createLoiApproval(sequelize);
db.LoiDocumentGenerated = createLoiDocumentGenerated(sequelize);
db.LoiAcknowledgement = createLoiAcknowledgement(sequelize);
db.SecurityDeposit = createSecurityDeposit(sequelize);
db.LoaRequest = createLoaRequest(sequelize);
db.LoaApproval = createLoaApproval(sequelize);
db.LoaDocumentGenerated = createLoaDocumentGenerated(sequelize);
db.LoaAcknowledgement = createLoaAcknowledgement(sequelize);
db.EorChecklist = createEorChecklist(sequelize);
db.EorChecklistItem = createEorChecklistItem(sequelize);

// Batch 6: Offboarding & F&F Settlement
db.TerminationRequest = createTerminationRequest(sequelize);
db.ExitFeedback = createExitFeedback(sequelize);

// Batch 7: Notifications, Logs & Templates
db.EmailTemplate = createEmailTemplate(sequelize);
db.PushSubscription = createPushSubscription(sequelize);

// Batch 8: SLA & TAT Tracking
db.SLATracking = createSLATracking(sequelize);
db.SLABreach = createSLABreach(sequelize);
db.SLANotificationDispatch = createSLANotificationDispatch(sequelize);
db.StageApprovalPolicy = createStageApprovalPolicy(sequelize);
db.StageApprovalAction = createStageApprovalAction(sequelize);
db.SystemConfiguration = createSystemConfiguration(sequelize);

// Batch 9: System internals
db.Migration = createMigration(sequelize);

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

db.sequelize = sequelize;
db.Sequelize = Sequelize;

export default db;
export { sequelize, Sequelize };
