import { type User, type InsertUser, type Label, type InsertLabel, type SharedLabel, type Task, type InsertTask, type XpEvent, type InsertXpEvent, type Goal, type InsertGoal, type Reward, type InsertReward, type UserReward, type InsertUserReward, type SystemSettings, type InsertSystemSettings, type SharedTask, type InsertSharedTask, type UserTaskAccess, type InsertUserTaskAccess, type InsertPasswordResetToken, type PasswordResetToken, type Conversation, type InsertConversation, type Message, type InsertMessage, type AuditLog, type InsertAuditLog } from "@shared/schema";
import * as schema from "@shared/schema";
import { getDatabase, pool } from "./db";
import { eq, sql, and, desc, asc, gt, ne } from "drizzle-orm";
import { randomUUID } from "crypto";
import session from "express-session";
import createMemoryStore from "memorystore";
import connectPg from "connect-pg-simple";

const MemoryStore = createMemoryStore(session);
const PostgresStore = connectPg(session);

export interface IStorage {
  sessionStore: session.Store;
  getUser(id: string): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  getUserByEmail(email: string): Promise<User | undefined>;
  getUserByApiKey(apiKey: string): Promise<User | undefined>;
  createUser(user: InsertUser & { role?: string; isActive?: boolean }): Promise<User>;
  updateUserApiKey(userId: string, apiKey: string | null): Promise<User>;
  updateUser(id: string, updates: Partial<User>): Promise<User>;
  deleteUser(id: string): Promise<boolean>;
  getAllUsers(): Promise<User[]>;
  updateUserXP(id: string, xp: number): Promise<void>;

  // Social & Leaderboard
  getLeaderboard(): Promise<User[]>;
  searchUsers(query: string): Promise<User[]>;
  shareTask(sharedTask: InsertSharedTask): Promise<SharedTask>;
  shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess>;
  createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask>; // Alias for shareTask standard naming
  createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess>; // Alias

  getSharedTasks(userId: string): Promise<SharedTask[]>; // Tasks shared WITH user
  getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]>; // Access Viewer has to Owners
  getTaskSharedUsers(taskId: string): Promise<User[]>; // Get users a task is shared WITH
  unshareTask(taskId: string, userId: string): Promise<boolean>; // Unshare specific task from user

  // Shared Labels
  shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission?: string): Promise<SharedLabel>;
  getSharedLabels(userId: string): Promise<SharedLabel[]>; // Labels shared WITH user
  getLabelSharedUsers(labelId: string): Promise<User[]>; // Users label is shared WITH
  unshareLabel(labelId: string, userId: string): Promise<boolean>;
  getLabelShares(labelId: string): Promise<SharedLabel[]>;

  // System Settings (Admin)
  getSystemSettings(key: string): Promise<string | undefined>;
  setSystemSettings(key: string, value: string): Promise<void>;
  hasAdminUser(): Promise<boolean>;

  // Labels
  getAllLabels(): Promise<Label[]>;
  getLabels(userId: string): Promise<Label[]>;
  getLabel(id: string): Promise<Label | undefined>;
  createLabel(label: InsertLabel): Promise<Label>;
  updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined>;
  deleteLabel(id: string): Promise<boolean>;

  // Tasks
  getTasksForUser(userId: string): Promise<Task[]>; // Replaces getAllTasks
  getTask(id: string): Promise<Task | undefined>;
  createTask(task: InsertTask & { userId?: string }): Promise<Task>;
  updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined>;
  deleteTask(id: string): Promise<boolean>;
  searchTasks(query: string, userId: string): Promise<Task[]>;
  getSubtasks(parentTaskId: string): Promise<Task[]>;

  // Gamification
  logXpEvent(event: InsertXpEvent): Promise<XpEvent>;
  getGoals(): Promise<Goal[]>;
  createGoal(goal: InsertGoal): Promise<Goal>;
  updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal>;

  // Rewards
  getAllRewards(): Promise<Reward[]>;
  getUserRewards(userId: string): Promise<UserReward[]>;
  createReward(reward: InsertReward): Promise<Reward>;
  createReward(reward: InsertReward): Promise<Reward>;
  createUserReward(userReward: InsertUserReward): Promise<UserReward>;
  getReward(id: string): Promise<Reward | undefined>;
  purchaseReward(userId: string, rewardId: string, cost: number): Promise<{ success: boolean; user: User; userReward: UserReward }>;

  // History
  getXpEvents(userId: string): Promise<XpEvent[]>;

  // Auth - Password Reset
  createPasswordResetToken(token: InsertPasswordResetToken): Promise<PasswordResetToken>;
  getPasswordResetToken(token: string): Promise<PasswordResetToken | undefined>;
  markPasswordResetTokenUsed(id: string): Promise<void>;

  // AI Chat
  createConversation(userId: string, title?: string): Promise<Conversation>;
  getConversations(userId: string): Promise<Conversation[]>;
  getConversation(id: string): Promise<Conversation | undefined>;
  updateConversation(id: string, title: string): Promise<Conversation | undefined>;
  deleteConversation(id: string): Promise<boolean>;
  addMessage(message: InsertMessage): Promise<Message>;
  getMessages(conversationId: string): Promise<Message[]>;
  getMessage(id: string): Promise<Message | undefined>;
  updateMessage(id: string, content: string): Promise<Message>;
  deleteMessagesAfter(conversationId: string, after: Date, excludeMessageId?: string): Promise<void>;

  // Audit Logs
  createAuditLog(log: InsertAuditLog): Promise<AuditLog>;
  getAuditLogs(limit?: number): Promise<AuditLog[]>;
}

export class MemStorage implements IStorage {
  private users: Map<string, User>;
  private labels: Map<string, Label>;
  private tasks: Map<string, Task>;
  private xpEvents: Map<string, XpEvent>;
  private settings: Map<string, string>;
  private goals: Map<string, Goal>;
  private rewards: Map<string, Reward>;
  private userRewards: Map<string, UserReward>;

  // Social maps
  private sharedTasks: Map<string, SharedTask>;
  private sharedLabels: Map<string, SharedLabel>;
  private userTaskAccess: Map<string, UserTaskAccess>;
  private passwordResetTokens: Map<string, PasswordResetToken>; // id -> Token
  private auditLogs: Map<string, AuditLog>;

  sessionStore: session.Store;

  constructor() {
    this.users = new Map();
    this.labels = new Map();
    this.tasks = new Map();
    this.xpEvents = new Map();
    this.settings = new Map();
    this.goals = new Map();
    this.rewards = new Map();
    this.userRewards = new Map();
    this.sharedTasks = new Map();
    this.sharedLabels = new Map();
    this.userTaskAccess = new Map();
    this.passwordResetTokens = new Map();
    this.auditLogs = new Map();
    this.sessionStore = new MemoryStore({
      checkPeriod: 86400000,
    });

    // Create some default labels
    this.createDefaultLabels();
    this.createDefaultRewards();
  }

  // ... (createDefaultLabels)

  private async createDefaultLabels() {
    // Use fixed IDs to prevent ID churn on server restarts
    const defaultLabels = [
      { id: 'cb44bed1-8ba3-43fe-9498-bb28e483ed1f', name: "Work", color: "#3B82F6", creatorId: null },
      { id: '274f0ba4-a133-471a-bbe9-8189aa3b0106', name: "Personal", color: "#10B981", creatorId: null },
      { id: '2e8c3aa0-278f-4220-b2c5-aa109b4279b7', name: "Urgent", color: "#EF4444", creatorId: null },
      { id: 'c5eccac9-7919-4eb1-bb50-badacad6b1c1', name: "Study", color: "#8B5CF6", creatorId: null },
    ];
    for (const label of defaultLabels) {
      if (!this.labels.has(label.id)) {
        this.labels.set(label.id, label);
      }
    }
  }

  async getUser(id: string): Promise<User | undefined> {
    return this.users.get(id);
  }

  async getUserByUsername(username: string): Promise<User | undefined> {
    return Array.from(this.users.values()).find(
      (user) => user.username === username,
    );
  }

  async getUserByEmail(email: string): Promise<User | undefined> {
    return Array.from(this.users.values()).find(
      (user) => user.email === email,
    );
  }

  async getAllUsers(): Promise<User[]> {
    return Array.from(this.users.values());
  }

  async getUserByApiKey(apiKey: string): Promise<User | undefined> {
    return Array.from(this.users.values()).find(u => u.apiKey === apiKey);
  }

  async updateUserApiKey(userId: string, apiKey: string | null): Promise<User> {
    const user = this.users.get(userId);
    if (!user) throw new Error("User not found");
    const updated = { ...user, apiKey };
    this.users.set(userId, updated);
    return updated;
  }

  async createUser(insertUser: InsertUser & { role?: string; isActive?: boolean }): Promise<User> {
    const id = randomUUID();
    const user: User = {
      ...insertUser,
      id,
      role: insertUser.role || 'user',
      isActive: insertUser.isActive ?? true,
      email: insertUser.email || `missing_${id}@example.com`,
      xp: 0,
      level: 1,
      currentStreak: 0,
      lastTaskDate: null,
      showOnLeaderboard: insertUser.showOnLeaderboard ?? false,
      isSearchable: insertUser.isSearchable ?? false,
      apiKey: null,
      aiEnabled: insertUser.aiEnabled ?? true,
    };
    this.users.set(id, user);
    return user;
  }

  async updateUser(id: string, updates: Partial<User>): Promise<User> {
    const user = this.users.get(id);
    if (!user) throw new Error("User not found");
    // Ensure we don't accidentally override with undefined
    const updated = { ...user, ...updates };
    this.users.set(id, updated);
    return updated;
  }

  async deleteUser(id: string): Promise<boolean> {
    return this.users.delete(id);
  }

  // Social Methods (MemStorage)
  async getLeaderboard(): Promise<User[]> {
    return Array.from(this.users.values())
      .filter(u => u.showOnLeaderboard && u.isActive)
      .sort((a, b) => b.xp - a.xp);
  }

  async searchUsers(query: string): Promise<User[]> {
    if (!query || query.length < 2) return [];
    const lowerQ = query.toLowerCase();
    return Array.from(this.users.values()).filter(u =>
      u.isSearchable && u.isActive && u.username.toLowerCase().includes(lowerQ)
    );
  }

  async shareTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
    return this.createSharedTask(sharedTask);
  }

  async createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
    const id = randomUUID();
    const newItem: SharedTask = { ...sharedTask, id, createdAt: new Date() };
    this.sharedTasks.set(id, newItem);
    return newItem;
  }

  async shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
    return this.createUserTaskAccess(access);
  }

  async createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
    const id = randomUUID();
    const newItem: UserTaskAccess = { ...access, id, createdAt: new Date() };
    this.userTaskAccess.set(id, newItem);
    return newItem;
  }

  async getSharedTasks(userId: string): Promise<SharedTask[]> {
    return Array.from(this.sharedTasks.values()).filter(st => st.sharedWithUserId === userId);
  }

  async getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]> {
    return Array.from(this.userTaskAccess.values()).filter(uta => uta.viewerId === viewerId);
  }

  async getTaskSharedUsers(taskId: string): Promise<User[]> {
    const shares = Array.from(this.sharedTasks.values()).filter(st => st.taskId === taskId);
    const users: User[] = [];
    for (const share of shares) {
      const u = this.users.get(share.sharedWithUserId);
      if (u) users.push(u);
    }
    return users;
  }

  async unshareTask(taskId: string, userId: string): Promise<boolean> {
    let toDeleteId: string | null = null;
    for (const [id, share] of this.sharedTasks.entries()) {
      if (share.taskId === taskId && share.sharedWithUserId === userId) {
        toDeleteId = id;
        break;
      }
    }
    if (toDeleteId) {
      return this.sharedTasks.delete(toDeleteId);
    }
    return false;
  }

  // Shared Labels (MemStorage)
  async shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission: string = 'read'): Promise<SharedLabel> {
    const id = randomUUID();
    const share: SharedLabel = {
      id,
      labelId,
      sharedWithUserId,
      sharedByUserId,
      permission,
      createdAt: new Date()
    };
    this.sharedLabels.set(id, share);
    return share;
  }

  async getSharedLabels(userId: string): Promise<SharedLabel[]> {
    return Array.from(this.sharedLabels.values()).filter(sl => sl.sharedWithUserId === userId);
  }

  async getLabelSharedUsers(labelId: string): Promise<User[]> {
    const shares = Array.from(this.sharedLabels.values()).filter(sl => sl.labelId === labelId);
    const users: User[] = [];
    for (const share of shares) {
      const u = this.users.get(share.sharedWithUserId);
      if (u) users.push(u);
    }
    return users;
  }

  async unshareLabel(labelId: string, userId: string): Promise<boolean> {
    let toDeleteId: string | null = null;
    for (const [id, share] of this.sharedLabels.entries()) {
      if (share.labelId === labelId && share.sharedWithUserId === userId) {
        toDeleteId = id;
        break;
      }
    }
    if (toDeleteId) {
      return this.sharedLabels.delete(toDeleteId);
    }
    return false;
  }

  async getLabelShares(labelId: string): Promise<SharedLabel[]> {
    return Array.from(this.sharedLabels.values()).filter(sl => sl.labelId === labelId);
  }

  async getSystemSettings(key: string): Promise<string | undefined> {
    return this.settings.get(key);
  }

  async setSystemSettings(key: string, value: string): Promise<void> {
    this.settings.set(key, value);
  }

  async hasAdminUser(): Promise<boolean> {
    return Array.from(this.users.values()).some(u => u.role === 'admin');
  }

  // Labels
  async getAllLabels(): Promise<Label[]> {
    return Array.from(this.labels.values());
  }

  async getLabels(userId: string): Promise<Label[]> {
    return Array.from(this.labels.values()).filter(
      l => l.creatorId === null || l.creatorId === userId
    );
  }

  async getLabel(id: string): Promise<Label | undefined> {
    return this.labels.get(id);
  }

  async createLabel(insertLabel: InsertLabel): Promise<Label> {
    const id = randomUUID();
    const label: Label = {
      ...insertLabel,
      id,
      creatorId: insertLabel.creatorId ?? null
    };
    this.labels.set(id, label);
    return label;
  }

  async updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined> {
    const existing = this.labels.get(id);
    if (!existing) return undefined;

    const updated: Label = { ...existing, ...updates };
    this.labels.set(id, updated);
    return updated;
  }

  async deleteLabel(id: string): Promise<boolean> {
    return this.labels.delete(id);
  }

  // Tasks
  async getTasksForUser(userId: string): Promise<Task[]> {
    const allTasks = Array.from(this.tasks.values());

    // 1. My tasks
    const myTasks = allTasks.filter(t => t.userId === userId);

    // 2. Explicitly shared tasks (Single Task Share)
    const sharedToMe = Array.from(this.sharedTasks.values())
      .filter(st => st.sharedWithUserId === userId)
      .map(st => this.tasks.get(st.taskId))
      .filter((t): t is Task => !!t);

    // 3. Global Share Access (Share All)
    // Find users who have shared everything with ME (valid viewer)
    const accessGrants = Array.from(this.userTaskAccess.values())
      .filter(uta => uta.viewerId === userId);

    let globalSharedTasks: Task[] = [];
    if (accessGrants.length > 0) {
      const ownerIds = new Set(accessGrants.map(uta => uta.ownerId));
      globalSharedTasks = allTasks.filter(t => t.userId && ownerIds.has(t.userId));
    }

    // 4. Shared Labels
    // Find labels shared with me
    const sharedLabels = await this.getSharedLabels(userId);
    const sharedLabelIds = new Set(sharedLabels.map(sl => sl.labelId));
    const tasksFromSharedLabels = allTasks.filter(t => t.labelId && sharedLabelIds.has(t.labelId));

    // Merge and Dedupe
    const combined = [...myTasks, ...sharedToMe, ...globalSharedTasks, ...tasksFromSharedLabels];
    const unique = Array.from(new Map(combined.map(t => [t.id, t])).values());
    return unique;
  }

  async searchTasks(query: string, userId: string): Promise<Task[]> {
    const allTasks = await this.getTasksForUser(userId);
    if (!query) return allTasks;
    const lowerQuery = query.toLowerCase();
    return allTasks.filter(t =>
      t.title.toLowerCase().includes(lowerQuery) ||
      (t.description && t.description.toLowerCase().includes(lowerQuery))
    );
  }

  async getSubtasks(parentTaskId: string): Promise<Task[]> {
    return Array.from(this.tasks.values()).filter(t => t.parentTaskId === parentTaskId);
  }

  async getTask(id: string): Promise<Task | undefined> {
    return this.tasks.get(id);
  }

  async createTask(insertTask: InsertTask & { userId?: string }): Promise<Task> {
    const id = randomUUID();
    const task: Task = {
      id,
      title: insertTask.title,
      description: insertTask.description || null,
      status: insertTask.status || "todo",
      priority: insertTask.priority || "medium",
      dueDate: insertTask.dueDate || null,
      timeTracked: insertTask.timeTracked || 0,
      isTracking: insertTask.isTracking || false,
      projectId: insertTask.projectId || null,
      notes: insertTask.notes || null,
      labelId: insertTask.labelId || null,
      energyLevel: insertTask.energyLevel || "medium",

      estimatedDuration: insertTask.estimatedDuration || null,
      parentTaskId: insertTask.parentTaskId || null,
      startDate: insertTask.startDate || null,
      dependencies: insertTask.dependencies || null,
      userId: insertTask.userId || null // Set ownership
    };
    this.tasks.set(id, task);
    return task;
  }

  async updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined> {
    const existing = this.tasks.get(id);
    if (!existing) return undefined;

    const updated: Task = { ...existing, ...updates };
    this.tasks.set(id, updated);
    return updated;
  }

  async deleteTask(id: string): Promise<boolean> {
    return this.tasks.delete(id);
  }

  async updateUserXP(id: string, xp: number): Promise<void> {
    const user = this.users.get(id);
    if (user) {
      user.xp += xp;
      this.users.set(id, user);
    }
  }

  async logXpEvent(event: InsertXpEvent): Promise<XpEvent> {
    const id = randomUUID();
    const xpEvent: XpEvent = {
      ...event,
      id,
      userId: event.userId || null,
      taskId: event.taskId || null,
      createdAt: new Date()
    };
    this.xpEvents.set(id, xpEvent);
    // Also update user XP
    console.log("Mock update XP for user:", event.userId);
    return xpEvent;
  }

  async getGoals(): Promise<Goal[]> {
    return Array.from(this.goals.values());
  }

  async createGoal(goal: InsertGoal): Promise<Goal> {
    const id = randomUUID();
    const newGoal: Goal = {
      ...goal,
      id,
      userId: goal.userId || null,
      deadline: goal.deadline || null,
      current: 0,
      completed: false,
      createdAt: new Date()
    };
    this.goals.set(id, newGoal);
    return newGoal;
  }

  async updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal> {
    const existing = this.goals.get(id);
    if (!existing) throw new Error("Goal not found");
    const updated = { ...existing, ...updates };
    this.goals.set(id, updated);
    return updated;
  }


  // Rewards
  private async createDefaultRewards() {
    const defaultRewards = [
      { id: 'r1', title: "rewards.defaults.coffee.title", description: "rewards.defaults.coffee.description", cost: 50, icon: "coffee", type: "real_world", isSystem: true },
      { id: 'r2', title: "rewards.defaults.gaming.title", description: "rewards.defaults.gaming.description", cost: 100, icon: "gamepad-2", type: "real_world", isSystem: true },
      { id: 'r3', title: "rewards.defaults.theme.title", description: "rewards.defaults.theme.description", cost: 500, icon: "palette", type: "feature_unlock", isSystem: true },
    ];

    for (const r of defaultRewards) {
      if (!this.rewards.has(r.id)) {
        this.rewards.set(r.id, r as Reward);
      }
    }
  }

  async getAllRewards(): Promise<Reward[]> {
    return Array.from(this.rewards.values());
  }

  async getUserRewards(userId: string): Promise<UserReward[]> {
    return Array.from(this.userRewards.values()).filter(ur => ur.userId === userId);
  }

  async createReward(insertReward: InsertReward): Promise<Reward> {
    const id = randomUUID();
    const reward: Reward = {
      ...insertReward,
      id,
      type: insertReward.type || "virtual",
      description: insertReward.description || null,
      isSystem: false,
      userId: insertReward.userId || null
    };
    this.rewards.set(id, reward);
    return reward;
  }

  async createUserReward(insertUserReward: InsertUserReward): Promise<UserReward> {
    const id = randomUUID();
    const userReward: UserReward = {
      ...insertUserReward,
      id,
      userId: insertUserReward.userId || null,
      rewardId: insertUserReward.rewardId || null,
      purchasedAt: new Date()
    };
    this.userRewards.set(id, userReward);
    return userReward;
  }

  async getReward(id: string): Promise<Reward | undefined> {
    return this.rewards.get(id);
  }

  async purchaseReward(userId: string, rewardId: string, cost: number): Promise<{ success: boolean; user: User; userReward: UserReward }> {
    const user = this.users.get(userId);
    if (!user) throw new Error("User not found");
    if (user.xp < cost) throw new Error("Insufficient XP");

    // Deduct XP
    user.xp -= cost;
    this.users.set(userId, user);

    // Create User Reward
    const userReward = await this.createUserReward({ userId, rewardId });

    return { success: true, user, userReward };
  }

  async getXpEvents(userId: string): Promise<XpEvent[]> {
    return Array.from(this.xpEvents.values())
      .filter(e => e.userId === userId)
      .sort((a, b) => (b.createdAt && a.createdAt ? b.createdAt.getTime() - a.createdAt.getTime() : 0));
  }

  // Auth - Password Reset (MemStorage)
  async createPasswordResetToken(insertToken: InsertPasswordResetToken): Promise<PasswordResetToken> {
    const id = randomUUID();
    const token: PasswordResetToken = {
      ...insertToken,
      id,
      isUsed: false,
      createdAt: new Date()
    };
    this.passwordResetTokens.set(id, token);
    return token;
  }

  async getPasswordResetToken(tokenString: string): Promise<PasswordResetToken | undefined> {
    return Array.from(this.passwordResetTokens.values()).find(t => t.token === tokenString);
  }

  async markPasswordResetTokenUsed(id: string): Promise<void> {
    const token = this.passwordResetTokens.get(id);
    if (token) {
      token.isUsed = true;
      this.passwordResetTokens.set(id, token);
    }
  }

  // AI Chat Stubs
  async createConversation(userId: string, title?: string): Promise<Conversation> {
    throw new Error("MemStorage: AI Chat not implemented.");
  }
  async getConversations(userId: string): Promise<Conversation[]> {
    return [];
  }
  async getConversation(id: string): Promise<Conversation | undefined> {
    return undefined;
  }
  async deleteConversation(id: string): Promise<boolean> {
    return false;
  }
  async addMessage(message: InsertMessage): Promise<Message> {
    throw new Error("MemStorage: AI Chat not implemented.");
  }
  async getMessages(conversationId: string): Promise<Message[]> {
    return [];
  }
  async getMessage(id: string): Promise<Message | undefined> {
    return undefined;
  }
  async updateMessage(id: string, content: string): Promise<Message> {
    throw new Error("Not implemented");
  }
  async deleteMessagesAfter(conversationId: string, after: Date): Promise<void> {
    // No-op
  }
  async updateConversation(id: string, title: string): Promise<Conversation | undefined> {
    return undefined;
  }

  // Audit Logs (MemStorage)
  async createAuditLog(insertLog: InsertAuditLog): Promise<AuditLog> {
    const id = randomUUID();
    const log: AuditLog = {
      ...insertLog,
      id,
      userId: insertLog.userId || null,
      entityId: insertLog.entityId || null,
      details: insertLog.details || null,
      source: insertLog.source || "USER",
      createdAt: new Date(),
    };
    this.auditLogs.set(id, log);
    return log;
  }

  async getAuditLogs(limit = 100): Promise<AuditLog[]> {
    return Array.from(this.auditLogs.values())
      .sort((a, b) => (b.createdAt && a.createdAt ? b.createdAt.getTime() - a.createdAt.getTime() : 0))
      .slice(0, limit);
  }
}



export class DbStorage implements IStorage {
  private db = getDatabase();
  sessionStore: session.Store;

  constructor() {
    this.sessionStore = new PostgresStore({
      pool: pool ?? undefined,
      createTableIfMissing: true,
    });
  }

  async getUser(id: string): Promise<User | undefined> {
    const result = await this.db.select().from(schema.users).where(eq(schema.users.id, id));
    return result[0];
  }

  async getUserByUsername(username: string): Promise<User | undefined> {
    const result = await this.db.select().from(schema.users).where(eq(schema.users.username, username));
    return result[0];
  }

  async getUserByEmail(email: string): Promise<User | undefined> {
    const result = await this.db.select().from(schema.users).where(eq(schema.users.email, email));
    return result[0];
  }

  async getAllUsers(): Promise<User[]> {
    return await this.db.select().from(schema.users);
  }

  async getUserByApiKey(apiKey: string): Promise<User | undefined> {
    const result = await this.db.select().from(schema.users).where(eq(schema.users.apiKey, apiKey));
    return result[0];
  }

  async updateUserApiKey(userId: string, apiKey: string | null): Promise<User> {
    const result = await this.db.update(schema.users)
      .set({ apiKey })
      .where(eq(schema.users.id, userId))
      .returning();
    if (!result[0]) throw new Error("User not found");
    return result[0];
  }

  async createUser(insertUser: InsertUser & { role?: string; isActive?: boolean }): Promise<User> {
    const result = await this.db.insert(schema.users).values({
      ...insertUser,
      role: insertUser.role || 'user',
      isActive: insertUser.isActive ?? true,
      showOnLeaderboard: insertUser.showOnLeaderboard ?? false,
      isSearchable: insertUser.isSearchable ?? false,
    }).returning();
    return result[0];
  }

  async updateUser(id: string, updates: Partial<User>): Promise<User> {
    const result = await this.db.update(schema.users)
      .set(updates)
      .where(eq(schema.users.id, id))
      .returning();
    if (!result[0]) throw new Error("User not found");
    return result[0];
  }

  async deleteUser(id: string): Promise<boolean> {
    // Note: This relies on CASCADE DELETE foreign keys in schema,
    // otherwise we need to manually delete related records first.
    // For now, assuming schema handles it or we accept errors.
    const result = await this.db.delete(schema.users).where(eq(schema.users.id, id)).returning();
    return result.length > 0;
  }

  async getSystemSettings(key: string): Promise<string | undefined> {
    const result = await this.db.select().from(schema.systemSettings).where(eq(schema.systemSettings.key, key));
    return result[0]?.value;
  }

  async setSystemSettings(key: string, value: string): Promise<void> {
    // Upsert
    await this.db.insert(schema.systemSettings)
      .values({ key, value })
      .onConflictDoUpdate({ target: schema.systemSettings.key, set: { value, updatedAt: new Date() } });
  }

  async hasAdminUser(): Promise<boolean> {
    const result = await this.db.select().from(schema.users).where(eq(schema.users.role, 'admin')).limit(1);
    return result.length > 0;
  }

  async getAllLabels(): Promise<Label[]> {
    return await this.db.select().from(schema.labels);
  }

  async getLabels(userId: string): Promise<Label[]> {
    return await this.db.select().from(schema.labels).where(
      sql`${schema.labels.creatorId} IS NULL OR ${schema.labels.creatorId} = ${userId}`
    );
  }

  async getLabel(id: string): Promise<Label | undefined> {
    const result = await this.db.select().from(schema.labels).where(eq(schema.labels.id, id));
    return result[0];
  }

  async createLabel(insertLabel: InsertLabel): Promise<Label> {
    const result = await this.db.insert(schema.labels).values(insertLabel).returning();
    return result[0];
  }

  async updateLabel(id: string, updates: Partial<InsertLabel>): Promise<Label | undefined> {
    const result = await this.db
      .update(schema.labels)
      .set(updates)
      .where(eq(schema.labels.id, id))
      .returning();
    return result[0];
  }

  async deleteLabel(id: string): Promise<boolean> {
    const result = await this.db.delete(schema.labels).where(eq(schema.labels.id, id)).returning();
    return result.length > 0;
  }

  async getTasksForUser(userId: string): Promise<Task[]> {
    // 1. My tasks
    const result = await this.db.select().from(schema.tasks).where(eq(schema.tasks.userId, userId));

    // 2. Shared Tasks
    const sharedLinks = await this.db.select().from(schema.sharedTasks).where(eq(schema.sharedTasks.sharedWithUserId, userId));
    const sharedTaskIds = sharedLinks.map(s => s.taskId);
    let sharedTasks: Task[] = [];
    if (sharedTaskIds.length > 0) {
      sharedTasks = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.id} IN ${sharedTaskIds}`);
    }

    // 3. Global Access
    const accessGrants = await this.db.select().from(schema.userTaskAccess).where(eq(schema.userTaskAccess.viewerId, userId));
    const ownerIds = accessGrants.map(a => a.ownerId);
    let globalTasks: Task[] = [];
    if (ownerIds.length > 0) {
      globalTasks = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.userId} IN ${ownerIds}`);
    }

    // 4. Shared Labels
    const sharedLabels = await this.db.select().from(schema.sharedLabels).where(eq(schema.sharedLabels.sharedWithUserId, userId));
    const sharedLabelIds = sharedLabels.map(sl => sl.labelId);
    let tasksFromSharedLabels: Task[] = [];
    if (sharedLabelIds.length > 0) {
      tasksFromSharedLabels = await this.db.select().from(schema.tasks).where(sql`${schema.tasks.labelId} IN ${sharedLabelIds}`);
    }

    const combined = [...result, ...sharedTasks, ...globalTasks, ...tasksFromSharedLabels];
    const unique = Array.from(new Map(combined.map(t => [t.id, t])).values());
    return unique;
  }

  async searchTasks(query: string, userId: string): Promise<Task[]> {
    const allTasks = await this.getTasksForUser(userId);
    if (!query) return allTasks;
    const lowerQuery = query.toLowerCase();
    return allTasks.filter(t =>
      t.title.toLowerCase().includes(lowerQuery) ||
      (t.description && t.description.toLowerCase().includes(lowerQuery))
    );
  }

  async getSubtasks(parentTaskId: string): Promise<Task[]> {
    return await this.db.select().from(schema.tasks).where(eq(schema.tasks.parentTaskId, parentTaskId));
  }

  async getTask(id: string): Promise<Task | undefined> {
    const result = await this.db.select().from(schema.tasks).where(eq(schema.tasks.id, id));
    return result[0];
  }

  async createTask(insertTask: InsertTask & { userId?: string }): Promise<Task> {
    const result = await this.db.insert(schema.tasks).values(insertTask).returning();
    return result[0];
  }

  async updateTask(id: string, updates: Partial<InsertTask>): Promise<Task | undefined> {
    const result = await this.db
      .update(schema.tasks)
      .set(updates)
      .where(eq(schema.tasks.id, id))
      .returning();
    return result[0];
  }

  async deleteTask(id: string): Promise<boolean> {
    const result = await this.db.delete(schema.tasks).where(eq(schema.tasks.id, id)).returning();
    return result.length > 0;
  }

  async updateUserXP(id: string, xp: number): Promise<void> {
    const user = await this.getUser(id);
    if (user) {
      await this.db.update(schema.users)
        .set({ xp: user.xp + xp })
        .where(eq(schema.users.id, id));
    }
  }

  async logXpEvent(event: InsertXpEvent): Promise<XpEvent> {
    const result = await this.db.insert(schema.xpEvents).values(event).returning();
    // Also update user XP
    if (event.userId) { // In real app ensure ID
      await this.updateUserXP(event.userId, event.amount);
    }
    return result[0];
  }

  async getGoals(): Promise<Goal[]> {
    return await this.db.select().from(schema.goals);
  }

  async createGoal(goal: InsertGoal): Promise<Goal> {
    const result = await this.db.insert(schema.goals).values(goal).returning();
    return result[0];
  }

  async updateGoal(id: string, updates: Partial<InsertGoal & { completed?: boolean; current?: number }>): Promise<Goal> {
    const result = await this.db.update(schema.goals)
      .set(updates)
      .where(eq(schema.goals.id, id))
      .returning();
    if (!result[0]) throw new Error("Goal not found");
    return result[0];
  }

  async getAllRewards(): Promise<Reward[]> {
    return await this.db.select().from(schema.rewards);
  }

  async getUserRewards(userId: string): Promise<UserReward[]> {
    return await this.db.select().from(schema.userRewards).where(eq(schema.userRewards.userId, userId));
  }

  async createReward(insertReward: InsertReward): Promise<Reward> {
    const result = await this.db.insert(schema.rewards).values(insertReward).returning();
    return result[0];
  }

  async createUserReward(insertUserReward: InsertUserReward): Promise<UserReward> {
    const result = await this.db.insert(schema.userRewards).values(insertUserReward).returning();
    return result[0];
  }

  async getReward(id: string): Promise<Reward | undefined> {
    const result = await this.db.select().from(schema.rewards).where(eq(schema.rewards.id, id));
    return result[0];
  }

  async purchaseReward(userId: string, rewardId: string, cost: number): Promise<{ success: boolean; user: User; userReward: UserReward }> {
    return await this.db.transaction(async (tx) => {
      // 1. Get User and verify XP
      const userRes = await tx.select().from(schema.users).where(eq(schema.users.id, userId));
      const user = userRes[0];
      if (!user) throw new Error("User not found");
      if (user.xp < cost) throw new Error("Insufficient XP");

      // 2. Deduct XP
      const updatedUserRes = await tx.update(schema.users)
        .set({ xp: user.xp - cost })
        .where(eq(schema.users.id, userId))
        .returning();

      // 3. Create User Reward
      const urRes = await tx.insert(schema.userRewards).values({
        userId,
        rewardId,
        purchasedAt: new Date()
      }).returning();

      return { success: true, user: updatedUserRes[0], userReward: urRes[0] };
    });
  }

  async getXpEvents(userId: string): Promise<XpEvent[]> {
    return await this.db.select().from(schema.xpEvents).where(eq(schema.xpEvents.userId, userId));
  }

  async createPasswordResetToken(insertToken: InsertPasswordResetToken): Promise<PasswordResetToken> {
    const result = await this.db.insert(schema.passwordResetTokens).values(insertToken).returning();
    return result[0];
  }

  async getPasswordResetToken(token: string): Promise<PasswordResetToken | undefined> {
    const result = await this.db.select().from(schema.passwordResetTokens).where(eq(schema.passwordResetTokens.token, token));
    return result[0];
  }

  async markPasswordResetTokenUsed(id: string): Promise<void> {
    await this.db.update(schema.passwordResetTokens)
      .set({ isUsed: true })
      .where(eq(schema.passwordResetTokens.id, id));
  }

  // AI Chat Implementation
  async createConversation(userId: string, title?: string): Promise<Conversation> {
    const result = await this.db.insert(schema.conversations).values({
      userId,
      title: title || "New Chat",
      createdAt: new Date(),
      updatedAt: new Date()
    }).returning();
    return result[0];
  }

  async getConversations(userId: string): Promise<Conversation[]> {
    return await this.db.select()
      .from(schema.conversations)
      .where(eq(schema.conversations.userId, userId))
      .orderBy(desc(schema.conversations.updatedAt));
  }

  async getConversation(id: string): Promise<Conversation | undefined> {
    const result = await this.db.select().from(schema.conversations).where(eq(schema.conversations.id, id));
    return result[0];
  }

  async deleteConversation(id: string): Promise<boolean> {
    await this.db.delete(schema.messages).where(eq(schema.messages.conversationId, id));
    const result = await this.db.delete(schema.conversations).where(eq(schema.conversations.id, id)).returning();
    return result.length > 0;
  }

  async addMessage(message: InsertMessage): Promise<Message> {
    const result = await this.db.insert(schema.messages).values(message).returning();
    if (message.conversationId) {
      await this.db.update(schema.conversations)
        .set({ updatedAt: new Date() })
        .where(eq(schema.conversations.id, message.conversationId));
    }
    return result[0];
  }



  // Social & Leaderboard
  async getLeaderboard(): Promise<User[]> {
    return await this.db.select().from(schema.users)
      .where(and(eq(schema.users.isActive, true), eq(schema.users.showOnLeaderboard, true)))
      .orderBy(desc(schema.users.xp));
  }

  async searchUsers(query: string): Promise<User[]> {
    if (!query || query.length < 2) return [];
    return await this.db.select().from(schema.users)
      .where(and(
        eq(schema.users.isSearchable, true),
        eq(schema.users.isActive, true),
        sql`${schema.users.username} ILIKE ${'%' + query + '%'}`
      ));
  }

  async shareTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
    const result = await this.db.insert(schema.sharedTasks).values(sharedTask).returning();
    return result[0];
  }

  async shareAllTasks(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
    const result = await this.db.insert(schema.userTaskAccess).values(access).returning();
    return result[0];
  }

  async createSharedTask(sharedTask: InsertSharedTask): Promise<SharedTask> {
    return this.shareTask(sharedTask);
  }

  async createUserTaskAccess(access: InsertUserTaskAccess): Promise<UserTaskAccess> {
    return this.shareAllTasks(access);
  }

  async getSharedTasks(userId: string): Promise<SharedTask[]> {
    return await this.db.select().from(schema.sharedTasks).where(eq(schema.sharedTasks.sharedWithUserId, userId));
  }

  async getUserTaskAccess(viewerId: string): Promise<UserTaskAccess[]> {
    return await this.db.select().from(schema.userTaskAccess).where(eq(schema.userTaskAccess.viewerId, viewerId));
  }

  async getTaskSharedUsers(taskId: string): Promise<User[]> {
    const shares = await this.db.select().from(schema.sharedTasks).where(eq(schema.sharedTasks.taskId, taskId));
    if (shares.length === 0) return [];

    return await this.db.select().from(schema.users)
      .where(sql`${schema.users.id} IN ${shares.map(s => s.sharedWithUserId)}`);
  }

  async unshareTask(taskId: string, userId: string): Promise<boolean> {
    const result = await this.db.delete(schema.sharedTasks)
      .where(and(eq(schema.sharedTasks.taskId, taskId), eq(schema.sharedTasks.sharedWithUserId, userId)))
      .returning();
    return result.length > 0;
  }

  async shareLabel(labelId: string, sharedWithUserId: string, sharedByUserId: string, permission: string = 'read'): Promise<SharedLabel> {
    const result = await this.db.insert(schema.sharedLabels).values({
      labelId,
      sharedWithUserId,
      sharedByUserId,
      permission,
      createdAt: new Date()
    }).returning();
    return result[0];
  }

  async getSharedLabels(userId: string): Promise<SharedLabel[]> {
    return await this.db.select().from(schema.sharedLabels).where(eq(schema.sharedLabels.sharedWithUserId, userId));
  }

  async getLabelSharedUsers(labelId: string): Promise<User[]> {
    const shares = await this.db.select().from(schema.sharedLabels).where(eq(schema.sharedLabels.labelId, labelId));
    if (shares.length === 0) return [];
    return await this.db.select().from(schema.users)
      .where(sql`${schema.users.id} IN ${shares.map(s => s.sharedWithUserId)}`);
  }

  async unshareLabel(labelId: string, userId: string): Promise<boolean> {
    const result = await this.db.delete(schema.sharedLabels)
      .where(and(eq(schema.sharedLabels.labelId, labelId), eq(schema.sharedLabels.sharedWithUserId, userId)))
      .returning();
    return result.length > 0;
  }

  async getLabelShares(labelId: string): Promise<SharedLabel[]> {
    return await this.db.select().from(schema.sharedLabels).where(eq(schema.sharedLabels.labelId, labelId));
  }

  async updateConversation(id: string, title: string): Promise<Conversation | undefined> {
    const result = await this.db.update(schema.conversations)
      .set({ title, updatedAt: new Date() })
      .where(eq(schema.conversations.id, id))
      .returning();
    return result[0];
  }
  async getMessages(conversationId: string): Promise<Message[]> {
    return await this.db.select()
      .from(schema.messages)
      .where(eq(schema.messages.conversationId, conversationId))
      .orderBy(asc(schema.messages.createdAt));
  }

  async getMessage(id: string): Promise<Message | undefined> {
    const result = await this.db.select().from(schema.messages).where(eq(schema.messages.id, id));
    return result[0];
  }

  async updateMessage(id: string, content: string): Promise<Message> {
    const result = await this.db.update(schema.messages)
      .set({ content })
      .where(eq(schema.messages.id, id))
      .returning();
    return result[0];
  }

  async deleteMessagesAfter(conversationId: string, after: Date, excludeMessageId?: string): Promise<void> {
    const filters = [
      eq(schema.messages.conversationId, conversationId),
      gt(schema.messages.createdAt, after)
    ];

    if (excludeMessageId) {
      filters.push(ne(schema.messages.id, excludeMessageId));
    }

    await this.db.delete(schema.messages)
      .where(and(...filters));
  }

  // Audit Logs (DbStorage)
  async createAuditLog(insertLog: InsertAuditLog): Promise<AuditLog> {
    const result = await this.db.insert(schema.auditLogs).values(insertLog).returning();
    return result[0];
  }

  async getAuditLogs(limit = 100): Promise<AuditLog[]> {
    return await this.db.select()
      .from(schema.auditLogs)
      .orderBy(desc(schema.auditLogs.createdAt))
      .limit(limit);
  }
}

// Export storage based on environment
export const storage = process.env.NODE_ENV === 'production' || process.env.USE_DB === 'true'
  ? new DbStorage()
  : new MemStorage();
