import { mysqlTable, mysqlSchema, int, varchar, text, mysqlEnum, timestamp, index, json, decimal, bigint, float, tinyint, date, longtext } from "drizzle-orm/mysql-core"
import { sql } from "drizzle-orm"

export const achievements = mysqlTable("achievements", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 128 }).notNull(),
	description: text(),
	icon: text(),
	category: mysqlEnum(['gameplay','social','spending','milestone','special']).notNull(),
	condition: text().notNull(),
	rewardSc: int().default(0).notNull(),
	rewardGc: int().default(0).notNull(),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const aiEmployeeChats = mysqlTable("ai_employee_chats", {
	id: int().autoincrement().notNull(),
	employeeId: int().notNull(),
	userMessage: text().notNull(),
	assistantMessage: text().notNull(),
	createdAt: timestamp().defaultNow(),
});

export const aiEmployeeTasks = mysqlTable("ai_employee_tasks", {
	id: int().autoincrement().notNull(),
	title: varchar({ length: 255 }).notNull(),
	description: text().notNull(),
	assignedTo: int().notNull(),
	priority: mysqlEnum(['low','medium','high','urgent']).default('medium'),
	status: mysqlEnum(['pending','in_progress','completed','cancelled']).default('pending'),
	dueDate: varchar({ length: 50 }),
	createdAt: timestamp().defaultNow(),
	updatedAt: timestamp().defaultNow().onUpdateNow(),
});

export const aiEmployees = mysqlTable("ai_employees", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 100 }).notNull(),
	role: varchar({ length: 100 }).notNull(),
	department: varchar({ length: 100 }).notNull(),
	systemPrompt: text(),
	avatarUrl: text(),
	isActive: tinyint().default(1),
	tasksCompleted: int().default(0),
	totalChats: int().default(0),
	createdAt: timestamp().defaultNow(),
	updatedAt: timestamp().defaultNow().onUpdateNow(),
});

export const aiGeneratedGames = mysqlTable("ai_generated_games", {
	id: int().autoincrement().notNull(),
	originalGameId: int(),
	originalGameUrl: text(),
	gameName: varchar({ length: 255 }).notNull(),
	gameSlug: varchar({ length: 255 }).notNull(),
	description: text(),
	aiAnalysis: json(),
	reelSymbols: json(),
	bonusFeatures: json(),
	thumbnailUrl: text(),
	reelGraphicsUrl: json(),
	symbolGraphicsUrl: json(),
	rtp: decimal({ precision: 5, scale: 2 }).default('96').notNull(),
	volatility: mysqlEnum(['low','medium','high']).default('medium').notNull(),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("ai_generated_games_gameSlug_unique").on(table.gameSlug),
	index("idx_ai_games_slug").on(table.gameSlug),
]);

export const aiSocialContent = mysqlTable("ai_social_content", {
	id: int().autoincrement().notNull(),
	createdBy: int().notNull(),
	platform: mysqlEnum(['facebook','instagram','twitter','tiktok']).notNull(),
	prompt: text().notNull(),
	imageUrl: text().notNull(),
	caption: text(),
	hashtags: text(),
	isPublished: tinyint().default(0).notNull(),
	publishedAt: timestamp(),
	impressions: int().default(0).notNull(),
	clicks: int().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_social_content_platform").on(table.platform),
]);

export const auditLogs = mysqlTable("audit_logs", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	actorId: int(),
	actorRole: varchar({ length: 32 }),
	targetUserId: int(),
	action: varchar({ length: 128 }).notNull(),
	category: mysqlEnum(['auth','wallet','game','admin','kyc','staff','system','fraud']).notNull(),
	details: json(),
	ipAddress: varchar({ length: 64 }),
	userAgent: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_audit_actorId").on(table.actorId),
	index("idx_audit_createdAt").on(table.createdAt),
	index("idx_audit_category").on(table.category),
]);

export const bingoCards = mysqlTable("bingo_cards", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	sessionId: int().notNull(),
	userId: int().notNull(),
	roomId: int().notNull(),
	numbers: json().notNull(),
	daubed: json().notNull(),
	hasBingo: tinyint().default(0).notNull(),
	winAmount: decimal({ precision: 18, scale: 2 }).default('0.00'),
	purchasedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_cards_sessionId").on(table.sessionId),
	index("idx_cards_userId").on(table.userId),
]);

export const bingoRooms = mysqlTable("bingo_rooms", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 128 }).notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	ticketPrice: decimal({ precision: 10, scale: 2 }).notNull(),
	maxCards: int().default(4).notNull(),
	jackpot: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	jackpotBallLimit: int().default(76).notNull(),
	status: mysqlEnum(['open','calling','finished','paused']).default('open').notNull(),
	currentSession: int(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const bingoSessions = mysqlTable("bingo_sessions", {
	id: int().autoincrement().notNull(),
	roomId: int().notNull(),
	calledBalls: json().notNull(),
	ballCount: int().default(0).notNull(),
	prizePool: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	jackpotWon: tinyint().default(0).notNull(),
	winners: json(),
	status: mysqlEnum(['active','finished']).default('active').notNull(),
	startedAt: timestamp().defaultNow().notNull(),
	finishedAt: timestamp(),
});

export const casinoGames = mysqlTable("casino_games", {
	id: int().autoincrement().notNull(),
	slug: varchar({ length: 128 }).notNull(),
	title: varchar({ length: 255 }).notNull(),
	provider: varchar({ length: 128 }).notNull(),
	category: mysqlEnum(['slots','table','live','jackpot','new','popular','crash','instant']).notNull(),
	tags: json(),
	thumbnailUrl: text(),
	bannerUrl: text(),
	rtp: float().default(96).notNull(),
	volatility: mysqlEnum(['low','medium','high','very_high']).default('medium').notNull(),
	minBetGc: decimal({ precision: 10, scale: 2 }).default('1.00').notNull(),
	maxBetGc: decimal({ precision: 10, scale: 2 }).default('1000.00').notNull(),
	minBetSc: decimal({ precision: 10, scale: 2 }).default('0.10').notNull(),
	maxBetSc: decimal({ precision: 10, scale: 2 }).default('100.00').notNull(),
	isActive: tinyint().default(1).notNull(),
	isFeatured: tinyint().default(0).notNull(),
	isNew: tinyint().default(0).notNull(),
	playCount: bigint({ mode: "number" }).default(0).notNull(),
	description: text(),
	features: json(),
	paylines: int(),
	reels: int(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("casino_games_slug_unique").on(table.slug),
	index("idx_games_provider").on(table.provider),
	index("idx_games_category").on(table.category),
]);

export const chatMessages = mysqlTable("chat_messages", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	channel: varchar({ length: 64 }).default('global').notNull(),
	message: text().notNull(),
	isDeleted: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_chat_channel").on(table.channel),
]);

export const coinPackages = mysqlTable("coin_packages", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 128 }).notNull(),
	gcAmount: decimal({ precision: 18, scale: 2 }).notNull(),
	scBonusAmount: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	priceUsd: decimal({ precision: 10, scale: 2 }).notNull(),
	isPopular: tinyint().default(0).notNull(),
	isBestValue: tinyint().default(0).notNull(),
	isActive: tinyint().default(1).notNull(),
	sortOrder: int().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const dailyBonuses = mysqlTable("daily_bonuses", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gcAmount: decimal({ precision: 10, scale: 2 }).notNull(),
	scAmount: decimal({ precision: 10, scale: 2 }).notNull(),
	spinResult: int().notNull(),
	claimedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_daily_userId").on(table.userId),
]);

export const dailySpins = mysqlTable("daily_spins", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	spinsUsed: int().default(0).notNull(),
	lastSpinAt: timestamp(),
	lastResetAt: timestamp().defaultNow().notNull(),
	totalWon: decimal({ precision: 10, scale: 2 }).default('0.00').notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_daily_spins_userId").on(table.userId),
	index("idx_daily_spins_lastResetAt").on(table.lastResetAt),
]);

export const eventParticipation = mysqlTable("event_participation", {
	id: int().autoincrement().notNull(),
	eventId: int().notNull(),
	userId: int().notNull(),
	score: decimal({ precision: 15, scale: 2 }).default('0.00'),
	rewardClaimed: tinyint().default(0).notNull(),
	claimedAt: timestamp(),
	joinedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_event_participation_eventId").on(table.eventId),
	index("idx_event_participation_userId").on(table.userId),
]);

export const fraudAlerts = mysqlTable("fraud_alerts", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	alertType: mysqlEnum(['abnormal_rtp','rapid_betting','multi_account','bonus_abuse','unusual_withdrawal','velocity','pattern']).notNull(),
	severity: mysqlEnum(['low','medium','high','critical']).default('medium').notNull(),
	description: text().notNull(),
	details: json(),
	status: mysqlEnum(['open','investigating','resolved','dismissed']).default('open').notNull(),
	resolvedBy: int(),
	resolvedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_fraud_userId").on(table.userId),
	index("idx_fraud_status").on(table.status),
]);

export const friends = mysqlTable("friends", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	friendId: int().notNull(),
	status: mysqlEnum(['pending','accepted','blocked']).default('pending').notNull(),
	requestedAt: timestamp().defaultNow().notNull(),
	acceptedAt: timestamp(),
},
(table) => [
	index("idx_friends_unique").on(table.userId, table.friendId),
	index("idx_friends_userId").on(table.userId),
	index("idx_friends_friendId").on(table.friendId),
]);

export const gameAnalytics = mysqlTable("game_analytics", {
	id: int().autoincrement().notNull(),
	gameId: int().notNull(),
	totalSpins: int().default(0).notNull(),
	totalWagered: decimal({ precision: 15, scale: 2 }).default('0').notNull(),
	totalWon: decimal({ precision: 15, scale: 2 }).default('0').notNull(),
	totalRevenue: decimal({ precision: 15, scale: 2 }).default('0').notNull(),
	uniquePlayers: int().default(0).notNull(),
	avgBetSize: decimal({ precision: 10, scale: 2 }).default('0').notNull(),
	rtp: decimal({ precision: 5, scale: 2 }).default('96').notNull(),
	lastUpdated: timestamp().defaultNow().onUpdateNow().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_game_analytics_gameId").on(table.gameId),
]);

export const gameChat = mysqlTable("game_chat", {
	id: int().autoincrement().notNull(),
	gameId: int(),
	userId: int().notNull(),
	message: text().notNull(),
	isPublic: tinyint().default(1).notNull(),
	recipientId: int(),
	isPinned: tinyint().default(0).notNull(),
	isModerated: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_game_chat_gameId").on(table.gameId),
	index("idx_game_chat_userId").on(table.userId),
	index("idx_game_chat_createdAt").on(table.createdAt),
]);

export const gameSessions = mysqlTable("game_sessions", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	betAmount: decimal({ precision: 18, scale: 2 }).notNull(),
	winAmount: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	multiplier: float().notNull(),
	outcome: json(),
	rtpApplied: float(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_sessions_userId").on(table.userId),
	index("idx_sessions_gameId").on(table.gameId),
]);

export const jackpotHistory = mysqlTable("jackpot_history", {
	id: int().autoincrement().notNull(),
	jackpotId: int("jackpot_id").notNull(),
	userId: int("user_id").notNull(),
	gameId: int("game_id").notNull(),
	winAmount: decimal("win_amount", { precision: 18, scale: 2 }).notNull(),
	spinId: varchar("spin_id", { length: 64 }),
	createdAt: timestamp("created_at", { mode: 'string' }).default('CURRENT_TIMESTAMP').notNull(),
},
(table) => [
	index("idx_jackpot_history_jackpotId").on(table.jackpotId),
	index("idx_jackpot_history_userId").on(table.userId),
	index("idx_jackpot_history_createdAt").on(table.createdAt),
]);

export const kycDocuments = mysqlTable("kyc_documents", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	docType: mysqlEnum(['passport','drivers_license','national_id','utility_bill','bank_statement','selfie']).notNull(),
	fileUrl: text().notNull(),
	fileKey: text().notNull(),
	status: mysqlEnum(['pending','approved','rejected']).default('pending').notNull(),
	reviewedBy: int(),
	reviewNote: text(),
	submittedAt: timestamp().defaultNow().notNull(),
	reviewedAt: timestamp(),
});

export const leaderboards = mysqlTable("leaderboards", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	leaderboardType: mysqlEnum(['global','weekly','daily','game_specific']).notNull(),
	gameId: int(),
	totalWinnings: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	totalBets: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	winCount: int().default(0).notNull(),
	rank: int().default(0).notNull(),
	period: varchar({ length: 20 }),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_leaderboard_type").on(table.leaderboardType),
	index("idx_leaderboard_userId").on(table.userId),
	index("idx_leaderboard_gameId").on(table.gameId),
]);

export const miniGameRounds = mysqlTable("mini_game_rounds", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	gameType: mysqlEnum(['plinko','mines','dice','crash','wheel']).notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	betAmount: decimal({ precision: 18, scale: 2 }).notNull(),
	winAmount: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	multiplier: float().notNull(),
	serverSeed: varchar({ length: 128 }).notNull(),
	clientSeed: varchar({ length: 128 }),
	nonce: int().default(0).notNull(),
	outcome: json().notNull(),
	isVerified: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_minigame_userId").on(table.userId),
]);

export const multiplierBoosts = mysqlTable("multiplier_boosts", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	multiplier: decimal({ precision: 3, scale: 2 }).notNull(),
	reason: mysqlEnum(['event','achievement','vip_tier','promotional','referral']).notNull(),
	startAt: timestamp().notNull(),
	endAt: timestamp().notNull(),
	isActive: tinyint().default(1).notNull(),
	appliedGames: json(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_multiplier_userId").on(table.userId),
	index("idx_multiplier_isActive").on(table.isActive),
	index("idx_multiplier_endAt").on(table.endAt),
]);

export const notificationPreferences = mysqlTable("notification_preferences", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	emailNotifications: tinyint().default(1).notNull(),
	pushNotifications: tinyint().default(1).notNull(),
	inAppNotifications: tinyint().default(1).notNull(),
	paymentNotifications: tinyint().default(1).notNull(),
	gameNotifications: tinyint().default(1).notNull(),
	promotionalNotifications: tinyint().default(0).notNull(),
	systemAlerts: tinyint().default(1).notNull(),
	emailFrequency: mysqlEnum(['instant','daily','weekly','never']).default('instant').notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("notification_preferences_userId_unique").on(table.userId),
	index("idx_notif_prefs_userId").on(table.userId),
]);

export const notifications = mysqlTable("notifications", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	type: mysqlEnum(['payment_success','payment_failed','bonus_credited','game_win','game_loss','bet_placed','bet_settled','odds_changed','poker_table_joined','poker_hand_result','poker_tournament_update','bingo_card_purchased','bingo_number_called','bingo_win','kyc_approved','kyc_rejected','kyc_pending','account_suspended','account_restored','withdrawal_approved','withdrawal_rejected','system_alert','promotional','admin_broadcast']).notNull(),
	title: varchar({ length: 255 }).notNull(),
	message: text().notNull(),
	channels: json(),
	data: json(),
	isRead: tinyint().default(0).notNull(),
	readAt: timestamp(),
	emailSent: tinyint().default(0).notNull(),
	pushSent: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	expiresAt: timestamp(),
},
(table) => [
	index("idx_notifications_userId").on(table.userId),
	index("idx_notifications_createdAt").on(table.createdAt),
]);

export const paymentMethods = mysqlTable("payment_methods", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 100 }).notNull(),
	provider: varchar({ length: 100 }).notNull(),
	type: mysqlEnum(['purchase','redemption']).notNull(),
	feePercent: decimal({ precision: 5, scale: 2 }).default('0'),
	flatFee: decimal({ precision: 10, scale: 2 }).default('0'),
	minAmount: decimal({ precision: 10, scale: 2 }).default('0'),
	maxAmount: decimal({ precision: 10, scale: 2 }).default('10000'),
	isEnabled: tinyint().default(1),
	iconUrl: text(),
	description: text(),
	sortOrder: int().default(0),
	createdAt: timestamp().defaultNow(),
	updatedAt: timestamp().defaultNow().onUpdateNow(),
});

export const platformSettings = mysqlTable("platform_settings", {
	id: int().autoincrement().notNull(),
	settingKey: varchar("setting_key", { length: 100 }).notNull(),
	settingValue: text("setting_value").notNull(),
	description: text(),
	updatedAt: timestamp("updated_at", { mode: 'string' }).defaultNow().onUpdateNow(),
	updatedBy: varchar("updated_by", { length: 255 }),
},
(table) => [
	index("setting_key").on(table.settingKey),
]);

export const playerProfiles = mysqlTable("player_profiles", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	bio: text(),
	avatarUrl: text(),
	bannerUrl: text(),
	totalSpins: int().default(0).notNull(),
	totalWins: decimal({ precision: 15, scale: 2 }).default('0').notNull(),
	favoriteGame: varchar({ length: 128 }),
	level: int().default(1).notNull(),
	experience: int().default(0).notNull(),
	isPublic: tinyint().default(1).notNull(),
	facebookId: varchar({ length: 255 }),
	instagramHandle: varchar({ length: 255 }),
	twitterHandle: varchar({ length: 255 }),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("player_profiles_userId_unique").on(table.userId),
	index("idx_player_profiles_userId").on(table.userId),
]);

export const pokerHands = mysqlTable("poker_hands", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	tableId: int().notNull(),
	handNumber: int().notNull(),
	players: json().notNull(),
	communityCards: json(),
	pot: decimal({ precision: 18, scale: 2 }).notNull(),
	winners: json(),
	actions: json(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_hands_tableId").on(table.tableId),
]);

export const pokerTables = mysqlTable("poker_tables", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 128 }).notNull(),
	gameType: mysqlEnum(['holdem','omaha']).default('holdem').notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	smallBlind: decimal({ precision: 10, scale: 2 }).notNull(),
	bigBlind: decimal({ precision: 10, scale: 2 }).notNull(),
	minBuyIn: decimal({ precision: 10, scale: 2 }).notNull(),
	maxBuyIn: decimal({ precision: 10, scale: 2 }).notNull(),
	maxPlayers: int().default(9).notNull(),
	currentPlayers: int().default(0).notNull(),
	status: mysqlEnum(['waiting','active','paused','closed']).default('waiting').notNull(),
	tournamentId: int(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const pokerTournaments = mysqlTable("poker_tournaments", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	buyIn: decimal({ precision: 10, scale: 2 }).notNull(),
	prizePool: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	maxPlayers: int().notNull(),
	registeredPlayers: int().default(0).notNull(),
	startTime: timestamp().notNull(),
	status: mysqlEnum(['registering','running','finished','cancelled']).default('registering').notNull(),
	structure: json(),
	payoutStructure: json(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const poolSharkAchievements = mysqlTable("pool_shark_achievements", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	achievementType: mysqlEnum(['first_win','five_wins','ten_wins','fifty_wins','hundred_wins','pool_shark','hustler','legend','perfect_break','high_accuracy','winning_streak','prize_master']).notNull(),
	title: varchar({ length: 100 }).notNull(),
	description: text(),
	badgeUrl: text(),
	unlockedAt: timestamp().defaultNow().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_pool_shark_achievements_unique").on(table.userId, table.achievementType),
	index("idx_pool_shark_achievements_userId").on(table.userId),
	index("idx_pool_shark_achievements_type").on(table.achievementType),
]);

export const poolSharkLeaderboards = mysqlTable("pool_shark_leaderboards", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	totalMatches: int().default(0).notNull(),
	totalWins: int().default(0).notNull(),
	totalLosses: int().default(0).notNull(),
	winRate: decimal({ precision: 5, scale: 2 }).default('0.00').notNull(),
	totalPrizeWon: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	highestBreak: int().default(0).notNull(),
	averageAccuracy: decimal({ precision: 5, scale: 2 }).default('0.00').notNull(),
	totalBallsPocketed: int().default(0).notNull(),
	rank: int().default(0).notNull(),
	lastUpdated: timestamp().defaultNow().onUpdateNow().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("pool_shark_leaderboards_userId_unique").on(table.userId),
	index("idx_pool_shark_leaderboards_userId").on(table.userId),
	index("idx_pool_shark_leaderboards_rank").on(table.rank),
	index("idx_pool_shark_leaderboards_totalWins").on(table.totalWins),
]);

export const poolSharkMatches = mysqlTable("pool_shark_matches", {
	id: int().autoincrement().notNull(),
	tableId: int().notNull(),
	status: mysqlEnum(['waiting','in_progress','completed','cancelled']).default('waiting').notNull(),
	winnerId: int(),
	winnerBreak: int(),
	totalPrizePool: decimal({ precision: 10, scale: 2 }).notNull(),
	startedAt: timestamp(),
	completedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_pool_shark_matches_tableId").on(table.tableId),
	index("idx_pool_shark_matches_status").on(table.status),
	index("idx_pool_shark_matches_winnerId").on(table.winnerId),
	index("idx_pool_shark_matches_createdAt").on(table.createdAt),
]);

export const poolSharkParticipants = mysqlTable("pool_shark_participants", {
	id: int().autoincrement().notNull(),
	matchId: int().notNull(),
	userId: int().notNull(),
	entryFee: decimal({ precision: 10, scale: 2 }).notNull(),
	position: int(),
	prizeWon: decimal({ precision: 10, scale: 2 }).default('0.00').notNull(),
	ballsPocketed: int().default(0).notNull(),
	highestBreak: int().default(0).notNull(),
	shotsAttempted: int().default(0).notNull(),
	shotsMade: int().default(0).notNull(),
	accuracy: decimal({ precision: 5, scale: 2 }).default('0.00').notNull(),
	joinedAt: timestamp().defaultNow().notNull(),
	leftAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_pool_shark_participants_unique").on(table.matchId, table.userId),
	index("idx_pool_shark_participants_matchId").on(table.matchId),
	index("idx_pool_shark_participants_userId").on(table.userId),
]);

export const poolSharkTables = mysqlTable("pool_shark_tables", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 100 }).notNull(),
	description: text(),
	entryFee: decimal({ precision: 10, scale: 2 }).notNull(),
	maxPlayers: int().default(2).notNull(),
	minPlayers: int().default(2).notNull(),
	prizeMultiplier: decimal({ precision: 5, scale: 2 }).default('2.00').notNull(),
	status: mysqlEnum(['active','inactive','archived']).default('active').notNull(),
	sortOrder: int().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_pool_shark_tables_status").on(table.status),
	index("idx_pool_shark_tables_sortOrder").on(table.sortOrder),
]);

export const poolSharkWaitingLists = mysqlTable("pool_shark_waiting_lists", {
	id: int().autoincrement().notNull(),
	tableId: int().notNull(),
	userId: int().notNull(),
	position: int().notNull(),
	joinedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_pool_shark_waiting_lists_unique").on(table.tableId, table.userId),
	index("idx_pool_shark_waiting_lists_tableId").on(table.tableId),
	index("idx_pool_shark_waiting_lists_userId").on(table.userId),
]);

export const progressiveJackpots = mysqlTable("progressive_jackpots", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	description: text(),
	currentAmount: decimal("current_amount", { precision: 18, scale: 2 }).default('0').notNull(),
	baseAmount: decimal("base_amount", { precision: 18, scale: 2 }).default('100').notNull(),
	contributionPercentage: float("contribution_percentage").default(0.5).notNull(),
	winProbability: float("win_probability").default(0.0001).notNull(),
	maxWinAmount: decimal("max_win_amount", { precision: 18, scale: 2 }),
	isActive: tinyint("is_active").default(1).notNull(),
	gameIds: text("game_ids"),
	lastWonBy: int("last_won_by"),
	lastWonAt: timestamp("last_won_at", { mode: 'string' }),
	lastWonAmount: decimal("last_won_amount", { precision: 18, scale: 2 }),
	totalWins: int("total_wins").default(0).notNull(),
	createdAt: timestamp("created_at", { mode: 'string' }).default('CURRENT_TIMESTAMP').notNull(),
	updatedAt: timestamp("updated_at", { mode: 'string' }).defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_progressive_jackpots_isActive").on(table.isActive),
]);

export const promoBanners = mysqlTable("promo_banners", {
	id: int().autoincrement().notNull(),
	title: varchar({ length: 255 }).notNull(),
	subtitle: text(),
	description: text(),
	imageUrl: text(),
	linkUrl: text(),
	linkText: varchar({ length: 128 }),
	bgGradientFrom: varchar({ length: 32 }).default('#f59e0b'),
	bgGradientTo: varchar({ length: 32 }).default('#d97706'),
	textColor: varchar({ length: 32 }).default('#ffffff'),
	sortOrder: int().default(0).notNull(),
	isActive: tinyint().default(1).notNull(),
	startAt: timestamp(),
	endAt: timestamp(),
	createdByAdminId: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_promo_banners_isActive").on(table.isActive),
	index("idx_promo_banners_sortOrder").on(table.sortOrder),
]);

export const recentlyPlayed = mysqlTable("recently_played", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	playedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_recent_userId").on(table.userId),
]);

export const referrals = mysqlTable("referrals", {
	id: int().autoincrement().notNull(),
	referrerId: int().notNull(),
	refereeId: int().notNull(),
	referralCode: varchar({ length: 32 }).notNull(),
	referralLink: text().notNull(),
	source: mysqlEnum(['facebook','messenger','sms','twitter','instagram','email','other']).notNull(),
	status: mysqlEnum(['pending','completed','expired']).default('pending').notNull(),
	referrerRewardGiven: tinyint().default(0).notNull(),
	refereeRewardGiven: tinyint().default(0).notNull(),
	rewardAmount: int().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	completedAt: timestamp(),
},
(table) => [
	index("referrals_referralCode_unique").on(table.referralCode),
	index("idx_referrals_referrerId").on(table.referrerId),
	index("idx_referrals_refereeId").on(table.refereeId),
	index("idx_referrals_code").on(table.referralCode),
]);

export const restrictedStates = mysqlTable("restricted_states", {
	id: int().autoincrement().notNull(),
	stateCode: varchar({ length: 4 }).notNull(),
	stateName: varchar({ length: 128 }).notNull(),
	reason: text(),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("restricted_states_stateCode_unique").on(table.stateCode),
]);

export const rtpOverrides = mysqlTable("rtp_overrides", {
	id: int().autoincrement().notNull(),
	userId: int(),
	gameId: int(),
	rtpOverride: float().notNull(),
	setByAdminId: int().notNull(),
	reason: text(),
	expiresAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
});

export const scRedemptions = mysqlTable("sc_redemptions", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	scAmount: decimal({ precision: 18, scale: 2 }).notNull(),
	usdAmount: decimal({ precision: 18, scale: 2 }).notNull(),
	method: mysqlEnum(['bank_transfer','check','paypal','crypto']).notNull(),
	paymentDetails: json(),
	status: mysqlEnum(['pending','approved','processing','completed','rejected']).default('pending').notNull(),
	reviewedBy: int(),
	reviewNote: text(),
	createdAt: timestamp().defaultNow().notNull(),
	processedAt: timestamp(),
},
(table) => [
	index("idx_redemptions_userId").on(table.userId),
]);

export const seasonalEvents = mysqlTable("seasonal_events", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	description: text(),
	type: mysqlEnum(['tournament','promotion','special_game','bonus_multiplier']).notNull(),
	status: mysqlEnum(['upcoming','active','completed']).default('upcoming').notNull(),
	startAt: timestamp().notNull(),
	endAt: timestamp().notNull(),
	bannerUrl: text(),
	rewardType: mysqlEnum(['gc','sc','multiplier','exclusive_access']).notNull(),
	rewardAmount: int().default(0),
	participantCount: int().default(0),
	maxParticipants: int(),
	metadata: json(),
	createdBy: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_event_status").on(table.status),
	index("idx_event_startAt").on(table.startAt),
]);

export const socialStream = mysqlTable("social_stream", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	activityType: mysqlEnum(['win','achievement_unlocked','tournament_joined','vip_tier_upgrade','milestone_reached','friend_added']).notNull(),
	title: varchar({ length: 255 }).notNull(),
	description: text(),
	metadata: json(),
	visibility: mysqlEnum(['public','friends_only','private']).default('public').notNull(),
	likeCount: int().default(0).notNull(),
	commentCount: int().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_social_stream_userId").on(table.userId),
	index("idx_social_stream_activityType").on(table.activityType),
	index("idx_social_stream_createdAt").on(table.createdAt),
]);

export const spinHistory = mysqlTable("spin_history", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	amount: decimal({ precision: 10, scale: 2 }).notNull(),
	currency: mysqlEnum(['GC','SC']).default('SC').notNull(),
	result: varchar({ length: 50 }).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_spin_history_userId").on(table.userId),
	index("idx_spin_history_createdAt").on(table.createdAt),
]);

export const sportBets = mysqlTable("sport_bets", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	betType: mysqlEnum(['single','parlay','teaser']).default('single').notNull(),
	totalStake: decimal({ precision: 18, scale: 2 }).notNull(),
	totalOdds: float().notNull(),
	potentialPayout: decimal({ precision: 18, scale: 2 }).notNull(),
	actualPayout: decimal({ precision: 18, scale: 2 }).default('0.00'),
	status: mysqlEnum(['pending','won','lost','cancelled','partial_win','void']).default('pending').notNull(),
	selections: json().notNull(),
	settledAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_bets_userId").on(table.userId),
	index("idx_bets_status").on(table.status),
]);

export const sportEvents = mysqlTable("sport_events", {
	id: int().autoincrement().notNull(),
	sport: varchar({ length: 64 }).notNull(),
	league: varchar({ length: 128 }).notNull(),
	homeTeam: varchar({ length: 128 }).notNull(),
	awayTeam: varchar({ length: 128 }).notNull(),
	startTime: timestamp().notNull(),
	status: mysqlEnum(['upcoming','live','finished','cancelled','suspended']).default('upcoming').notNull(),
	homeScore: int().default(0),
	awayScore: int().default(0),
	period: varchar({ length: 32 }),
	odds: json(),
	metadata: json(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_events_sport").on(table.sport),
	index("idx_events_status").on(table.status),
]);

export const staff = mysqlTable("staff", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	staffId: varchar({ length: 32 }).notNull(),
	pin: varchar({ length: 255 }).notNull(),
	position: varchar({ length: 128 }).notNull(),
	department: varchar({ length: 128 }),
	hourlyRate: decimal({ precision: 10, scale: 2 }),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("staff_userId_unique").on(table.userId),
	index("staff_staffId_unique").on(table.staffId),
]);

export const streamInteractions = mysqlTable("stream_interactions", {
	id: int().autoincrement().notNull(),
	streamEntryId: int().notNull(),
	userId: int().notNull(),
	interactionType: mysqlEnum(['like','comment']).notNull(),
	content: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_stream_interactions_streamEntryId").on(table.streamEntryId),
	index("idx_stream_interactions_userId").on(table.userId),
]);

export const supportTickets = mysqlTable("support_tickets", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	assignedStaffId: int(),
	subject: varchar({ length: 255 }).notNull(),
	category: mysqlEnum(['account','payment','game','bonus','technical','kyc','other']).notNull(),
	priority: mysqlEnum(['low','medium','high','urgent']).default('medium').notNull(),
	status: mysqlEnum(['open','in_progress','waiting_user','resolved','closed']).default('open').notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
	resolvedAt: timestamp(),
},
(table) => [
	index("idx_tickets_userId").on(table.userId),
	index("idx_tickets_status").on(table.status),
]);

export const ticketMessages = mysqlTable("ticket_messages", {
	id: int().autoincrement().notNull(),
	ticketId: int().notNull(),
	senderId: int().notNull(),
	senderRole: mysqlEnum(['user','staff','admin']).notNull(),
	message: text().notNull(),
	attachmentUrl: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_messages_ticketId").on(table.ticketId),
]);

export const timeClock = mysqlTable("time_clock", {
	id: int().autoincrement().notNull(),
	staffId: int().notNull(),
	clockIn: timestamp().notNull(),
	clockOut: timestamp(),
	hoursWorked: float(),
	notes: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_timeclock_staffId").on(table.staffId),
]);

export const tournamentParticipants = mysqlTable("tournament_participants", {
	id: int().autoincrement().notNull(),
	tournamentId: int().notNull(),
	userId: int().notNull(),
	score: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	finalRank: int(),
	prizeWon: decimal({ precision: 15, scale: 2 }).default('0.00'),
	joinedAt: timestamp().defaultNow().notNull(),
	completedAt: timestamp(),
},
(table) => [
	index("idx_tournament_participants_tournamentId").on(table.tournamentId),
	index("idx_tournament_participants_userId").on(table.userId),
]);

export const tournamentSnapshots = mysqlTable("tournament_snapshots", {
	id: int().autoincrement().notNull(),
	tournamentId: int().notNull(),
	snapshotTime: timestamp().defaultNow().notNull(),
	topPlayers: json(),
},
(table) => [
	index("idx_tournament_snapshots_tournamentId").on(table.tournamentId),
]);

export const tournaments = mysqlTable("tournaments", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	description: text(),
	gameId: int(),
	status: mysqlEnum(['upcoming','active','completed','cancelled']).default('upcoming').notNull(),
	startAt: timestamp().notNull(),
	endAt: timestamp().notNull(),
	entryFeeGc: int().default(0).notNull(),
	maxParticipants: int(),
	currentParticipants: int().default(0).notNull(),
	prizePool: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	prizeDistribution: json(),
	leaderboardId: int(),
	createdBy: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_tournament_status").on(table.status),
	index("idx_tournament_gameId").on(table.gameId),
	index("idx_tournament_startAt").on(table.startAt),
]);

export const transactions = mysqlTable("transactions", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	type: mysqlEnum(['gc_purchase','gc_bonus','sc_bonus','sc_redeem','game_bet','game_win','sport_bet','sport_win','sport_refund','poker_buyin','poker_win','poker_rake','bingo_purchase','bingo_win','minigame_bet','minigame_win','daily_bonus','admin_credit','admin_debit','referral_bonus','promo_credit']).notNull(),
	currency: mysqlEnum(['GC','SC']).notNull(),
	amount: decimal({ precision: 18, scale: 2 }).notNull(),
	balanceBefore: decimal({ precision: 18, scale: 2 }).notNull(),
	balanceAfter: decimal({ precision: 18, scale: 2 }).notNull(),
	referenceId: varchar({ length: 128 }),
	referenceType: varchar({ length: 64 }),
	description: text(),
	metadata: json(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_transactions_userId").on(table.userId),
	index("idx_transactions_createdAt").on(table.createdAt),
]);

export const userAchievements = mysqlTable("user_achievements", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	achievementId: int().notNull(),
	unlockedAt: timestamp().defaultNow().notNull(),
	rewardClaimed: tinyint().default(0).notNull(),
},
(table) => [
	index("idx_user_achievements_unique").on(table.userId, table.achievementId),
	index("idx_user_achievements_userId").on(table.userId),
	index("idx_user_achievements_achievementId").on(table.achievementId),
]);

export const userFavorites = mysqlTable("user_favorites", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_user_favorites_unique").on(table.userId, table.gameId),
	index("idx_user_favorites_userId").on(table.userId),
	index("idx_user_favorites_gameId").on(table.gameId),
]);

export const userVipStatus = mysqlTable("user_vip_status", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	currentVipTierId: int(),
	lifetimeWinnings: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	totalBetsPlaced: decimal({ precision: 15, scale: 2 }).default('0.00').notNull(),
	weeklyBonusClaimedAt: timestamp(),
	monthlyBonusClaimedAt: timestamp(),
	lastVipUpgradeAt: timestamp(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("user_vip_status_userId_unique").on(table.userId),
	index("idx_user_vip_userId").on(table.userId),
]);

	export const users = mysqlTable("users", {
		id: int().autoincrement().notNull(),
		openId: varchar({ length: 64 }).notNull(),
		name: text(),
		email: varchar({ length: 320 }),
		loginMethod: varchar({ length: 64 }),
		role: mysqlEnum(['user','staff','admin']).default('user').notNull(),
		createdAt: timestamp().defaultNow().notNull(),
		updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
		lastSignedIn: timestamp().defaultNow().notNull(),
		username: varchar({ length: 64 }),
		passwordHash: varchar({ length: 255 }),
		twoFactorEnabled: tinyint().default(0).notNull(),
		twoFactorSecret: varchar({ length: 255 }),
	},
		(table) => [
			index("users_openId_unique").on(table.openId),
			index("users_username_unique").on(table.username),
		]);

	// Future columns to add when database is migrated:
	// kycStatus, kycLevel, isBanned, banReason, isAgeVerified, dateOfBirth,
	// stateCode, country, phone, phoneVerified, avatarUrl, socialProvider,
	// socialId, socialProfileData, lastIp, stripeCustomerId

export const vipTiers = mysqlTable("vip_tiers", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 64 }).notNull(),
	minLifetimeWinnings: decimal({ precision: 15, scale: 2 }).notNull(),
	bonusMultiplier: decimal({ precision: 3, scale: 2 }).default('1.00').notNull(),
	weeklyBonusGc: int().default(0).notNull(),
	monthlyBonusGc: int().default(0).notNull(),
	exclusiveGames: json(),
	prioritySupport: tinyint().default(0).notNull(),
	customAvatarFrame: tinyint().default(0).notNull(),
	badgeIcon: text(),
	description: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_vip_tier_minWinnings").on(table.minLifetimeWinnings),
]);

export const wallets = mysqlTable("wallets", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gcBalance: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	scBalance: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	lifetimeGcEarned: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	lifetimeScEarned: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	lifetimeScRedeemed: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
});

export const winShareEvents = mysqlTable("win_share_events", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	winAmount: decimal({ precision: 15, scale: 2 }).notNull(),
	shareMessage: text().notNull(),
	platform: mysqlEnum(['facebook','messenger','sms','twitter']).notNull(),
	referralCode: varchar({ length: 32 }).notNull(),
	sharedAt: timestamp().defaultNow().notNull(),
	clickCount: int().default(0).notNull(),
},
(table) => [
	index("idx_win_share_userId").on(table.userId),
	index("idx_win_share_gameId").on(table.gameId),
]);


export const customGames = mysqlTable("custom_games", {
	id: int().autoincrement().notNull(),
	createdBy: int().notNull(),
	gameName: varchar({ length: 255 }).notNull(),
	gameSlug: varchar({ length: 255 }).notNull(),
	description: text(),
	templateType: mysqlEnum(['three_reel','five_reel','bonus_heavy','progressive']).notNull(),
	thumbnailUrl: text(),
	reelCount: int().default(5).notNull(),
	paylineCount: int().default(25).notNull(),
	minBet: decimal({ precision: 10, scale: 2 }).default('0.01').notNull(),
	maxBet: decimal({ precision: 10, scale: 2 }).default('100.00').notNull(),
	rtp: decimal({ precision: 5, scale: 2 }).default('96.00').notNull(),
	volatility: mysqlEnum(['low','medium','high']).default('medium').notNull(),
	reelSymbols: json().notNull(),
	bonusFeatures: json(),
	scatterSymbol: varchar({ length: 50 }),
	wildSymbol: varchar({ length: 50 }),
	freeSpinsConfig: json(),
	multiplierConfig: json(),
	progressiveJackpot: tinyint().default(0).notNull(),
	isActive: tinyint().default(1).notNull(),
	isPublished: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("custom_games_gameSlug_unique").on(table.gameSlug),
	index("idx_custom_games_createdBy").on(table.createdBy),
	index("idx_custom_games_active").on(table.isActive),
]);


export const gameConfigurations = mysqlTable("game_configurations", {
	id: int().autoincrement().notNull(),
	gameId: int().notNull(),
	configKey: varchar({ length: 100 }).notNull(),
	configValue: json().notNull(),
	description: text(),
	isActive: tinyint().default(1).notNull(),
	updatedBy: int(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_game_config_gameId").on(table.gameId),
	index("idx_game_config_key").on(table.configKey),
]);

export const gameTemplates = mysqlTable("game_templates", {
	id: int().autoincrement().notNull(),
	templateName: varchar({ length: 100 }).notNull(),
	templateType: mysqlEnum(['three_reel','five_reel','bonus_heavy','progressive']).notNull(),
	description: text(),
	defaultConfig: json().notNull(),
	reelCount: int().default(5).notNull(),
	paylineCount: int().default(25).notNull(),
	symbolSet: json().notNull(),
	bonusFeatures: json(),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_game_templates_type").on(table.templateType),
]);


export const oauthAccounts = mysqlTable("oauth_accounts", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	provider: mysqlEnum(['google', 'github', 'apple']).notNull(),
	providerAccountId: varchar({ length: 255 }).notNull(),
	accessToken: text(),
	refreshToken: text(),
	expiresAt: timestamp(),
	scope: text(),
	tokenType: varchar({ length: 50 }),
	idToken: text(),
	sessionState: varchar({ length: 255 }),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_oauth_userId").on(table.userId),
	index("idx_oauth_provider_account").on(table.provider, table.providerAccountId),
]);

export const twoFactorSecrets = mysqlTable("two_factor_secrets", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	secret: varchar({ length: 255 }).notNull(),
	backupCodes: json(),
	isEnabled: tinyint().default(0).notNull(),
	enabledAt: timestamp(),
	lastVerifiedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_2fa_userId").on(table.userId),
]);

export const magicLinkTokens = mysqlTable("magic_link_tokens", {
	id: int().autoincrement().notNull(),
	token: varchar({ length: 255 }).notNull().unique(),
	email: varchar({ length: 255 }).notNull(),
	userId: int(),
	expiresAt: timestamp().notNull(),
	usedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_magic_token").on(table.token),
	index("idx_magic_email").on(table.email),
	index("idx_magic_expiresAt").on(table.expiresAt),
]);

export const authAuditLog = mysqlTable("auth_audit_log", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int(),
	email: varchar({ length: 255 }),
	action: mysqlEnum(['login', 'signup', 'logout', '2fa_enable', '2fa_disable', '2fa_verify', 'magic_link_send', 'magic_link_verify', 'oauth_link', 'oauth_unlink']).notNull(),
	provider: varchar({ length: 50 }),
	ipAddress: varchar({ length: 64 }),
	userAgent: text(),
	success: tinyint().default(1).notNull(),
	errorMessage: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_auth_audit_userId").on(table.userId),
	index("idx_auth_audit_action").on(table.action),
	index("idx_auth_audit_createdAt").on(table.createdAt),
]);

export const rateLimitLog = mysqlTable("rate_limit_log", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	ipAddress: varchar({ length: 64 }).notNull(),
	endpoint: varchar({ length: 255 }).notNull(),
	userId: int(),
	requestCount: int().default(1).notNull(),
	windowStart: timestamp().notNull(),
	windowEnd: timestamp().notNull(),
	isBlocked: tinyint().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_ratelimit_ip_endpoint").on(table.ipAddress, table.endpoint),
	index("idx_ratelimit_isBlocked").on(table.isBlocked),
]);

// Session Management Table
export const userSessions = mysqlTable("user_sessions", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	sessionToken: varchar({ length: 255 }).notNull().unique(),
	deviceName: varchar({ length: 255 }).notNull(),
	deviceType: varchar({ length: 50 }).notNull(),
	osName: varchar({ length: 100 }),
	osVersion: varchar({ length: 50 }),
	browserName: varchar({ length: 100 }),
	browserVersion: varchar({ length: 50 }),
	ipAddress: varchar({ length: 64 }).notNull(),
	userAgent: text(),
	lastActivityAt: timestamp().defaultNow(),
	expiresAt: timestamp().notNull(),
	isActive: tinyint().default(1).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_sessions_user_id").on(table.userId),
	index("idx_sessions_token").on(table.sessionToken),
	index("idx_sessions_expires").on(table.expiresAt),
]);

export type UserSession = typeof userSessions.$inferSelect;
export type NewUserSession = typeof userSessions.$inferInsert;


// PGSOFT Games Tables
export const pgSoftGames = mysqlTable("pgsoft_games", {
	id: int().autoincrement().notNull(),
	gameCode: varchar({ length: 100 }).notNull().unique(),
	pgSoftCode: int().notNull(),
	name: varchar({ length: 255 }).notNull(),
	slug: varchar({ length: 255 }).notNull(),
	description: text(),
	category: varchar({ length: 50 }).default('slots').notNull(),
	thumbnailUrl: text(),
	bannerUrl: text(),
	rtp: decimal({ precision: 5, scale: 2 }).default('96.0').notNull(),
	volatility: mysqlEnum(['low','medium','high','very_high']).default('medium').notNull(),
	minBet: decimal({ precision: 10, scale: 2 }).default('0.10').notNull(),
	maxBet: decimal({ precision: 10, scale: 2 }).default('1000.00').notNull(),
	paylines: int().default(50).notNull(),
	reels: int().default(5).notNull(),
	features: json(),
	isActive: tinyint().default(1).notNull(),
	isNew: tinyint().default(0).notNull(),
	isFeatured: tinyint().default(0).notNull(),
	playCount: bigint({ mode: "number" }).default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_pgsoft_games_slug").on(table.slug),
	index("idx_pgsoft_games_category").on(table.category),
	index("idx_pgsoft_games_active").on(table.isActive),
]);

export const pgSoftGameSessions = mysqlTable("pgsoft_game_sessions", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	gameCode: varchar({ length: 100 }).notNull(),
	sessionToken: varchar({ length: 255 }).notNull().unique(),
	userBalance: decimal({ precision: 18, scale: 2 }).notNull(),
	initialBalance: decimal({ precision: 18, scale: 2 }).notNull(),
	finalBalance: decimal({ precision: 18, scale: 2 }),
	totalWin: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	totalLoss: decimal({ precision: 18, scale: 2 }).default('0.00').notNull(),
	spinCount: int().default(0).notNull(),
	status: mysqlEnum(['active','completed','abandoned']).default('active').notNull(),
	launchUrl: text(),
	ipAddress: varchar({ length: 64 }),
	userAgent: text(),
	startedAt: timestamp().defaultNow().notNull(),
	endedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_pgsoft_sessions_userId").on(table.userId),
	index("idx_pgsoft_sessions_gameId").on(table.gameId),
	index("idx_pgsoft_sessions_token").on(table.sessionToken),
	index("idx_pgsoft_sessions_status").on(table.status),
]);

export const pgSoftGameTransactions = mysqlTable("pgsoft_game_transactions", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	sessionId: bigint({ mode: "number" }).notNull(),
	userId: int().notNull(),
	gameId: int().notNull(),
	transactionType: mysqlEnum(['bet','win','bonus','refund']).notNull(),
	amount: decimal({ precision: 18, scale: 2 }).notNull(),
	balanceBefore: decimal({ precision: 18, scale: 2 }).notNull(),
	balanceAfter: decimal({ precision: 18, scale: 2 }).notNull(),
	spinNumber: int(),
	details: json(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_pgsoft_trans_sessionId").on(table.sessionId),
	index("idx_pgsoft_trans_userId").on(table.userId),
	index("idx_pgsoft_trans_type").on(table.transactionType),
]);

export type PGSoftGame = typeof pgSoftGames.$inferSelect;
export type NewPGSoftGame = typeof pgSoftGames.$inferInsert;
export type PGSoftGameSession = typeof pgSoftGameSessions.$inferSelect;
export type NewPGSoftGameSession = typeof pgSoftGameSessions.$inferInsert;
export type PGSoftGameTransaction = typeof pgSoftGameTransactions.$inferSelect;
export type NewPGSoftGameTransaction = typeof pgSoftGameTransactions.$inferInsert;


// ─── MULTI-GAME SYSTEM (365+ GAMES) ──────────────────────────────────────────

export const allGames = mysqlTable("all_games", {
	id: int().autoincrement().notNull(),
	gameId: varchar({ length: 100 }).notNull().unique(),
	gameName: varchar({ length: 255 }).notNull(),
	gameType: varchar({ length: 50 }).notNull(),
	category: varchar({ length: 50 }).default("slots").notNull(),
	provider: varchar({ length: 100 }).notNull(),
	rtp: decimal({ precision: 5, scale: 2 }).default("96.00").notNull(),
	volatility: varchar({ length: 20 }).default("medium").notNull(),
	paylines: int().default(20).notNull(),
	reels: int().default(5).notNull(),
	minBet: decimal({ precision: 10, scale: 2 }).default("0.01").notNull(),
	maxBet: decimal({ precision: 10, scale: 2 }).default("100.00").notNull(),
	jackpot: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	hasIcon: tinyint().default(0).notNull(),
	iconUrl: text(),
	thumbnail_url: text(),
	gameUrl: text(),
	isActive: tinyint().default(1).notNull(),
	isFeatured: tinyint().default(0).notNull(),
	playCount: int().default(0).notNull(),
	totalWinnings: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	averageWin: decimal({ precision: 10, scale: 2 }).default("0").notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_all_games_gameId").on(table.gameId),
	index("idx_all_games_provider").on(table.provider),
	index("idx_all_games_category").on(table.category),
]);

export const gameLibrary = mysqlTable("game_library", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gameId: varchar({ length: 100 }).notNull(),
	lastPlayedAt: timestamp(),
	favorited: tinyint().default(0).notNull(),
	playCount: int().default(0).notNull(),
	totalBet: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	totalWin: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_game_library_userId").on(table.userId),
	index("idx_game_library_gameId").on(table.gameId),
]);

export const gameStats = mysqlTable("game_stats", {
	id: int().autoincrement().notNull(),
	gameId: varchar({ length: 100 }).notNull(),
	date: varchar({ length: 10 }).notNull(),
	playCount: int().default(0).notNull(),
	uniquePlayers: int().default(0).notNull(),
	totalBet: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	totalWin: decimal({ precision: 15, scale: 2 }).default("0").notNull(),
	totalRtp: decimal({ precision: 5, scale: 2 }).default("0").notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_game_stats_gameId").on(table.gameId),
	index("idx_game_stats_date").on(table.date),
]);

export const gameRecommendations = mysqlTable("game_recommendations", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	gameId: varchar({ length: 100 }).notNull(),
	score: decimal({ precision: 5, scale: 2 }).default("0").notNull(),
	reason: varchar({ length: 255 }),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_game_rec_userId").on(table.userId),
	index("idx_game_rec_gameId").on(table.gameId),
]);

export type AllGame = typeof allGames.$inferSelect;
export type NewAllGame = typeof allGames.$inferInsert;
export type GameLibraryEntry = typeof gameLibrary.$inferSelect;
export type NewGameLibraryEntry = typeof gameLibrary.$inferInsert;
export type GameStat = typeof gameStats.$inferSelect;
export type NewGameStat = typeof gameStats.$inferInsert;
export type GameRecommendation = typeof gameRecommendations.$inferSelect;
export type NewGameRecommendation = typeof gameRecommendations.$inferInsert;

export const emailVerifications = mysqlTable("email_verifications", {
	id: int().autoincrement().notNull(),
	userId: int().notNull(),
	email: varchar({ length: 255 }).notNull(),
	token: varchar({ length: 255 }).notNull().unique(),
	expiresAt: timestamp().notNull(),
	verifiedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
});

export type EmailVerification = typeof emailVerifications.$inferSelect;
export type NewEmailVerification = typeof emailVerifications.$inferInsert;

// Admin Onboarding Tables
export const adminOnboardingProgress = mysqlTable("admin_onboarding_progress", {
	id: int().autoincrement().notNull(),
	adminId: int().notNull(),
	currentStep: mysqlEnum(['welcome', 'role_assignment', 'permission_training', 'security_training', 'device_registration', 'completion']).default('welcome').notNull(),
	completedSteps: json().default(sql`(json_array())`).notNull(),
	roleAssigned: mysqlEnum(['super_admin', 'admin', 'moderator', 'finance_team', 'developer', 'support_lead']),
	permissionsAcknowledged: tinyint().default(0).notNull(),
	securityTrainingCompleted: tinyint().default(0).notNull(),
	securityQuizScore: int(),
	deviceRegistered: tinyint().default(0).notNull(),
	deviceName: varchar({ length: 255 }),
	deviceBrowser: varchar({ length: 100 }),
	deviceOs: varchar({ length: 100 }),
	deviceIpAddress: varchar({ length: 64 }),
	onboardingEnabled: tinyint().default(0).notNull(),
	startedAt: timestamp().defaultNow().notNull(),
	completedAt: timestamp(),
	lastActivityAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_admin_onboarding_adminId").on(table.adminId),
	index("idx_admin_onboarding_currentStep").on(table.currentStep),
	index("idx_admin_onboarding_completedAt").on(table.completedAt),
]);

export const adminProfiles = mysqlTable("admin_profiles", {
	id: int().autoincrement().notNull(),
	adminId: int().notNull(),
	avatarUrl: text(),
	phoneNumber: varchar({ length: 20 }),
	timezone: varchar({ length: 64 }).default('UTC').notNull(),
	language: varchar({ length: 10 }).default('en').notNull(),
	notificationPreferences: json(),
	twoFactorEnabled: tinyint().default(0).notNull(),
	twoFactorSecret: varchar({ length: 255 }),
	backupCodes: json(),
	lastProfileUpdateAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_admin_profiles_adminId").on(table.adminId),
]);

export const adminDeviceRegistrations = mysqlTable("admin_device_registrations", {
	id: int().autoincrement().notNull(),
	adminId: int().notNull(),
	deviceId: varchar({ length: 255 }).notNull(),
	deviceName: varchar({ length: 255 }).notNull(),
	browser: varchar({ length: 100 }).notNull(),
	os: varchar({ length: 100 }).notNull(),
	ipAddress: varchar({ length: 64 }).notNull(),
	userAgent: text(),
	isActive: tinyint().default(1).notNull(),
	lastUsedAt: timestamp().defaultNow().onUpdateNow(),
	registeredAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_admin_devices_adminId").on(table.adminId),
	index("idx_admin_devices_deviceId").on(table.deviceId),
]);

export const onboardingAnalytics = mysqlTable("onboarding_analytics", {
	id: int().autoincrement().notNull(),
	totalAdmins: int().default(0).notNull(),
	completedOnboardings: int().default(0).notNull(),
	pendingOnboardings: int().default(0).notNull(),
	averageCompletionTimeMinutes: int(),
	averageQuizScore: decimal({ precision: 5, scale: 2 }),
	stepCompletionRates: json(),
	roleDistribution: json(),
	dateRecorded: varchar({ length: 10 }).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_onboarding_analytics_date").on(table.dateRecorded),
]);

export type AdminOnboardingProgress = typeof adminOnboardingProgress.$inferSelect;
export type NewAdminOnboardingProgress = typeof adminOnboardingProgress.$inferInsert;
export type AdminProfile = typeof adminProfiles.$inferSelect;
export type NewAdminProfile = typeof adminProfiles.$inferInsert;
export type AdminDeviceRegistration = typeof adminDeviceRegistrations.$inferSelect;
export type NewAdminDeviceRegistration = typeof adminDeviceRegistrations.$inferInsert;
	export type OnboardingAnalytic = typeof onboardingAnalytics.$inferSelect;
export type NewOnboardingAnalytic = typeof onboardingAnalytics.$inferInsert;

// Shift Management Tables
export const adminShifts = mysqlTable("admin_shifts", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 100 }).notNull(),
	startTime: varchar({ length: 5 }).notNull(), // HH:MM format
	endTime: varchar({ length: 5 }).notNull(),
	shiftDate: date().notNull(),
	requiredCount: int().default(1).notNull(),
	status: mysqlEnum(['open', 'filled', 'overfilled']).default('open').notNull(),
	createdBy: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_admin_shifts_date").on(table.shiftDate),
	index("idx_admin_shifts_status").on(table.status),
]);

export const adminShiftAssignments = mysqlTable("admin_shift_assignments", {
	id: int().autoincrement().notNull(),
	shiftId: int().notNull(),
	adminId: int().notNull(),
	assignedBy: int().notNull(),
	status: mysqlEnum(['assigned', 'confirmed', 'completed', 'no_show']).default('assigned').notNull(),
	assignedAt: timestamp().defaultNow().notNull(),
	confirmedAt: timestamp(),
	completedAt: timestamp(),
},
(table) => [
	index("idx_shift_assignments_shiftId").on(table.shiftId),
	index("idx_shift_assignments_adminId").on(table.adminId),
]);

export const adminShiftSwaps = mysqlTable("admin_shift_swaps", {
	id: int().autoincrement().notNull(),
	requestingAdminId: int().notNull(),
	requestingWithAdminId: int().notNull(),
	fromShiftId: int().notNull(),
	toShiftId: int().notNull(),
	status: mysqlEnum(['pending', 'approved', 'rejected', 'cancelled']).default('pending').notNull(),
	reason: text(),
	responseNotes: text(),
	requestedAt: timestamp().defaultNow().notNull(),
	respondedAt: timestamp(),
},
(table) => [
	index("idx_shift_swaps_requestingAdminId").on(table.requestingAdminId),
	index("idx_shift_swaps_status").on(table.status),
]);

// Knowledge Base Tables
export const knowledgeArticles = mysqlTable("knowledge_articles", {
	id: int().autoincrement().notNull(),
	title: varchar({ length: 255 }).notNull(),
	category: varchar({ length: 100 }).notNull(),
	content: longtext().notNull(),
	tags: json(), // Array of strings
	author: int().notNull(),
	featured: tinyint().default(0).notNull(),
	viewCount: int().default(0).notNull(),
	helpfulCount: int().default(0).notNull(),
	unhelpfulCount: int().default(0).notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_knowledge_articles_category").on(table.category),
	index("idx_knowledge_articles_featured").on(table.featured),
	index("idx_knowledge_articles_author").on(table.author),
]);

export const knowledgeArticleVotes = mysqlTable("knowledge_article_votes", {
	id: int().autoincrement().notNull(),
	articleId: int().notNull(),
	adminId: int().notNull(),
	helpful: tinyint().notNull(), // 1 for helpful, 0 for unhelpful
	votedAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_article_votes_articleId").on(table.articleId),
	index("idx_article_votes_adminId").on(table.adminId),
]);

// Delegation Tables
export const adminDelegations = mysqlTable("admin_delegations", {
	id: int().autoincrement().notNull(),
	title: varchar({ length: 255 }).notNull(),
	description: text(),
	assigneeId: int().notNull(),
	delegatedBy: int().notNull(),
	priority: mysqlEnum(['low', 'medium', 'high', 'critical']).default('medium').notNull(),
	category: varchar({ length: 100 }),
	status: mysqlEnum(['pending', 'in-progress', 'completed', 'cancelled']).default('pending').notNull(),
	progress: int().default(0).notNull(),
	dueDate: date().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	completedAt: timestamp(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_delegations_assigneeId").on(table.assigneeId),
	index("idx_delegations_status").on(table.status),
	index("idx_delegations_dueDate").on(table.dueDate),
]);

export const adminDelegationNotes = mysqlTable("admin_delegation_notes", {
	id: int().autoincrement().notNull(),
	delegationId: int().notNull(),
	authorId: int().notNull(),
	content: text().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_delegation_notes_delegationId").on(table.delegationId),
]);

export const adminDelegationApprovals = mysqlTable("admin_delegation_approvals", {
	id: int().autoincrement().notNull(),
	delegationId: int().notNull(),
	approverId: int().notNull(),
	status: mysqlEnum(['pending', 'approved', 'rejected']).default('pending').notNull(),
	comments: text(),
	approvedAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_delegation_approvals_delegationId").on(table.delegationId),
	index("idx_delegation_approvals_approverId").on(table.approverId),
]);

// Type exports
export type AdminShift = typeof adminShifts.$inferSelect;
export type NewAdminShift = typeof adminShifts.$inferInsert;
export type AdminShiftAssignment = typeof adminShiftAssignments.$inferSelect;
export type NewAdminShiftAssignment = typeof adminShiftAssignments.$inferInsert;
export type AdminShiftSwap = typeof adminShiftSwaps.$inferSelect;
export type NewAdminShiftSwap = typeof adminShiftSwaps.$inferInsert;
export type KnowledgeArticle = typeof knowledgeArticles.$inferSelect;
export type NewKnowledgeArticle = typeof knowledgeArticles.$inferInsert;
export type KnowledgeArticleVote = typeof knowledgeArticleVotes.$inferSelect;
export type NewKnowledgeArticleVote = typeof knowledgeArticleVotes.$inferInsert;
export type AdminDelegation = typeof adminDelegations.$inferSelect;
export type NewAdminDelegation = typeof adminDelegations.$inferInsert;
export type AdminDelegationNote = typeof adminDelegationNotes.$inferSelect;
export type NewAdminDelegationNote = typeof adminDelegationNotes.$inferInsert;
export type AdminDelegationApproval = typeof adminDelegationApprovals.$inferSelect;
export type NewAdminDelegationApproval = typeof adminDelegationApprovals.$inferInsert;

// Email Campaigns
export const emailCampaigns = mysqlTable("email_campaigns", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	subject: varchar({ length: 255 }).notNull(),
	template: longtext().notNull(),
	recipientSegment: mysqlEnum(['all', 'vip', 'new', 'inactive', 'high-value']).default('all').notNull(),
	status: mysqlEnum(['draft', 'scheduled', 'sent']).default('draft').notNull(),
	scheduledTime: timestamp(),
	sentAt: timestamp(),
	recipientCount: int().default(0),
	openCount: int().default(0),
	clickCount: int().default(0),
	createdBy: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_email_campaigns_status").on(table.status),
	index("idx_email_campaigns_createdBy").on(table.createdBy),
	index("idx_email_campaigns_scheduledTime").on(table.scheduledTime),
]);

// Banner Analytics
export const bannerAnalytics = mysqlTable("banner_analytics", {
	id: int().autoincrement().notNull(),
	bannerId: varchar({ length: 255 }).notNull(),
	date: date().notNull(),
	impressions: int().default(0).notNull(),
	clicks: int().default(0).notNull(),
	conversions: int().default(0).notNull(),
	revenue: decimal({ precision: 10, scale: 2 }).default('0').notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_banner_analytics_bannerId").on(table.bannerId),
	index("idx_banner_analytics_date").on(table.date),
	index("idx_banner_analytics_bannerId_date").on(table.bannerId, table.date),
]);

// Type exports for new tables
export type EmailCampaign = typeof emailCampaigns.$inferSelect;
export type NewEmailCampaign = typeof emailCampaigns.$inferInsert;
export type BannerAnalytic = typeof bannerAnalytics.$inferSelect;
export type NewBannerAnalytic = typeof bannerAnalytics.$inferInsert;

// Admin Notifications
export const adminNotifications = mysqlTable("admin_notifications", {
	id: int().autoincrement().notNull(),
	type: mysqlEnum(['fraud_alert', 'large_win', 'kyc_pending', 'kyc_approved', 'kyc_rejected', 'system_alert', 'user_report', 'payment_issue', 'game_error']).notNull(),
	title: varchar({ length: 255 }).notNull(),
	message: text().notNull(),
	severity: mysqlEnum(['low', 'medium', 'high', 'critical']).default('medium').notNull(),
	relatedUserId: int(),
	relatedEntityId: varchar({ length: 255 }),
	relatedEntityType: varchar({ length: 64 }),
	data: json(),
	isRead: tinyint().default(0).notNull(),
	readAt: timestamp(),
	actionUrl: text(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_admin_notifications_type").on(table.type),
	index("idx_admin_notifications_severity").on(table.severity),
	index("idx_admin_notifications_isRead").on(table.isRead),
	index("idx_admin_notifications_createdAt").on(table.createdAt),
]);

// Webhooks Configuration
export const webhookConfigs = mysqlTable("webhook_configs", {
	id: int().autoincrement().notNull(),
	name: varchar({ length: 255 }).notNull(),
	url: text().notNull(),
	events: json().notNull(), // Array of event types to subscribe to
	headers: json(), // Custom headers to send with webhook
	isActive: tinyint().default(1).notNull(),
	secret: varchar({ length: 255 }).notNull(), // For HMAC signature verification
	retryCount: int().default(3).notNull(),
	retryDelay: int().default(300).notNull(), // seconds
	timeout: int().default(30).notNull(), // seconds
	createdBy: int().notNull(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_webhook_configs_isActive").on(table.isActive),
	index("idx_webhook_configs_createdBy").on(table.createdBy),
]);

// Webhook Delivery Log
export const webhookDeliveries = mysqlTable("webhook_deliveries", {
	id: bigint({ mode: "number" }).autoincrement().notNull(),
	webhookConfigId: int().notNull(),
	eventType: varchar({ length: 128 }).notNull(),
	payload: json().notNull(),
	statusCode: int(),
	responseBody: text(),
	error: text(),
	attemptNumber: int().default(1).notNull(),
	nextRetryAt: timestamp(),
	deliveredAt: timestamp(),
	createdAt: timestamp().defaultNow().notNull(),
},
(table) => [
	index("idx_webhook_deliveries_webhookConfigId").on(table.webhookConfigId),
	index("idx_webhook_deliveries_eventType").on(table.eventType),
	index("idx_webhook_deliveries_createdAt").on(table.createdAt),
	index("idx_webhook_deliveries_nextRetryAt").on(table.nextRetryAt),
]);

// Notification Preferences
export const adminNotificationPreferences = mysqlTable("admin_notification_preferences", {
	id: int().autoincrement().notNull(),
	adminId: int().notNull(),
	notificationType: varchar({ length: 128 }).notNull(),
	enabled: tinyint().default(1).notNull(),
	channels: json().notNull(), // ['email', 'push', 'websocket', 'sms']
	quietHoursStart: varchar({ length: 5 }), // HH:MM format
	quietHoursEnd: varchar({ length: 5 }),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_admin_notification_preferences_adminId").on(table.adminId),
	index("idx_admin_notification_preferences_notificationType").on(table.notificationType),
]);

// Type exports for notifications
export type AdminNotification = typeof adminNotifications.$inferSelect;
export type NewAdminNotification = typeof adminNotifications.$inferInsert;
export type WebhookConfig = typeof webhookConfigs.$inferSelect;
export type NewWebhookConfig = typeof webhookConfigs.$inferInsert;
export type WebhookDelivery = typeof webhookDeliveries.$inferSelect;
export type NewWebhookDelivery = typeof webhookDeliveries.$inferInsert;
export type AdminNotificationPreference = typeof adminNotificationPreferences.$inferSelect;
export type NewAdminNotificationPreference = typeof adminNotificationPreferences.$inferInsert;

// Social Media Campaign Tables
export const socialMediaCampaigns = mysqlTable("social_media_campaigns", {
	id: int().autoincrement().notNull().primaryKey(),
	createdBy: int().notNull(),
	campaignName: varchar({ length: 255 }).notNull(),
	description: text(),
	targetPlatforms: json().notNull(), // ['twitter', 'instagram', 'tiktok', 'facebook']
	postingFrequency: mysqlEnum(['daily', 'weekly', 'bi_weekly', 'monthly']).default('weekly'),
	status: mysqlEnum(['draft', 'scheduled', 'active', 'paused', 'completed']).default('draft'),
	startDate: timestamp(),
	endDate: timestamp(),
	totalPostsPlanned: int().default(0),
	totalPostsPublished: int().default(0),
	totalImpressions: int().default(0),
	totalEngagement: int().default(0),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_social_campaigns_createdBy").on(table.createdBy),
	index("idx_social_campaigns_status").on(table.status),
]);

export const socialMediaPosts = mysqlTable("social_media_posts", {
	id: int().autoincrement().notNull().primaryKey(),
	campaignId: int().notNull(),
	platform: mysqlEnum(['twitter', 'instagram', 'tiktok', 'facebook']).notNull(),
	caption: text().notNull(),
	imageUrl: text(),
	videoUrl: text(),
	hashtags: text(),
	mentions: text(),
	callToAction: varchar({ length: 255 }),
	status: mysqlEnum(['draft', 'scheduled', 'published', 'failed']).default('draft'),
	scheduledAt: timestamp(),
	publishedAt: timestamp(),
	impressions: int().default(0),
	clicks: int().default(0),
	likes: int().default(0),
	shares: int().default(0),
	comments: int().default(0),
	postUrl: text(),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_social_posts_campaignId").on(table.campaignId),
	index("idx_social_posts_platform").on(table.platform),
	index("idx_social_posts_status").on(table.status),
]);

export const aiGameBuilderConfigs = mysqlTable("ai_game_builder_configs", {
	id: int().autoincrement().notNull().primaryKey(),
	createdBy: int().notNull(),
	gameType: mysqlEnum(['slot', 'card', 'dice', 'puzzle', 'roulette', 'bingo', 'scratch']).notNull(),
	gameName: varchar({ length: 255 }).notNull(),
	description: text(),
	theme: varchar({ length: 100 }),
	difficulty: mysqlEnum(['easy', 'medium', 'hard']).default('medium'),
	rtp: decimal({ precision: 5, scale: 2 }).default('96'),
	volatility: mysqlEnum(['low', 'medium', 'high']).default('medium'),
	maxWin: int(),
	minBet: decimal({ precision: 10, scale: 2 }),
	maxBet: decimal({ precision: 10, scale: 2 }),
	gameRules: json(),
	gameMechanics: json(),
	bonusFeatures: json(),
	status: mysqlEnum(['draft', 'review', 'approved', 'published', 'archived']).default('draft'),
	createdAt: timestamp().defaultNow().notNull(),
	updatedAt: timestamp().defaultNow().onUpdateNow().notNull(),
},
(table) => [
	index("idx_game_configs_createdBy").on(table.createdBy),
	index("idx_game_configs_status").on(table.status),
	index("idx_game_configs_gameType").on(table.gameType),
]);

// Type exports for users
export type User = typeof users.$inferSelect;
export type InsertUser = typeof users.$inferInsert;
// Type exports for Pool Shark
export type PoolSharkTable = typeof poolSharkTables.$inferSelect;
export type NewPoolSharkTable = typeof poolSharkTables.$inferInsert;
export type PoolSharkMatch = typeof poolSharkMatches.$inferSelect;
export type NewPoolSharkMatch = typeof poolSharkMatches.$inferInsert;
export type PoolSharkParticipant = typeof poolSharkParticipants.$inferSelect;
export type NewPoolSharkParticipant = typeof poolSharkParticipants.$inferInsert;
export type PoolSharkLeaderboard = typeof poolSharkLeaderboards.$inferSelect;
export type NewPoolSharkLeaderboard = typeof poolSharkLeaderboards.$inferInsert;
export type PoolSharkAchievement = typeof poolSharkAchievements.$inferSelect;
export type NewPoolSharkAchievement = typeof poolSharkAchievements.$inferInsert;
export type PoolSharkWaitingList = typeof poolSharkWaitingLists.$inferSelect;
export type NewPoolSharkWaitingList = typeof poolSharkWaitingLists.$inferInsert;

// Type exports for AI Game Builder and Social Media
export type SocialMediaCampaign = typeof socialMediaCampaigns.$inferSelect;
export type NewSocialMediaCampaign = typeof socialMediaCampaigns.$inferInsert;
export type SocialMediaPost = typeof socialMediaPosts.$inferSelect;
export type NewSocialMediaPost = typeof socialMediaPosts.$inferInsert;
export type AIGameBuilderConfig = typeof aiGameBuilderConfigs.$inferSelect;
export type NewAIGameBuilderConfig = typeof aiGameBuilderConfigs.$inferInsert;
