import { sql } from "drizzle-orm";
import {
  pgTable,
  text,
  varchar,
  integer,
  timestamp,
  boolean,
  real,
  index,
  jsonb,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

// Session storage table - required for Replit Auth
export const sessions = pgTable(
  "sessions",
  {
    sid: varchar("sid").primaryKey(),
    sess: jsonb("sess").notNull(),
    expire: timestamp("expire").notNull(),
  },
  (table) => [index("IDX_session_expire").on(table.expire)]
);

// Users table - adapted for Replit Auth with custom fields
export const users = pgTable("users", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  email: varchar("email").unique(),
  firstName: varchar("first_name"),
  lastName: varchar("last_name"),
  profileImageUrl: varchar("profile_image_url"),
  planLimit: integer("plan_limit").notNull().default(10),
  isAdmin: boolean("is_admin").notNull().default(false),
  notificationsEnabled: boolean("notifications_enabled").notNull().default(true),
  aiSuggestionsEnabled: boolean("ai_suggestions_enabled").notNull().default(true),
  timezone: varchar("timezone").default("UTC"),
  language: varchar("language").default("en"),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow(),
});

// Plans table
export const plans = pgTable("plans", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  userId: varchar("user_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  planName: text("plan_name").notNull(),
  planDescription: text("plan_description"),
  category: varchar("category").default("personal"), // personal, business, study, custom
  priority: varchar("priority").default("medium"), // low, medium, high
  targetDate: timestamp("target_date"),
  notes: text("notes"),
  progressPercent: real("progress_percent").notNull().default(0),
  createdAt: timestamp("created_at").notNull().defaultNow(),
  updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

// Plan steps table
export const planSteps = pgTable("plan_steps", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  planId: varchar("plan_id")
    .notNull()
    .references(() => plans.id, { onDelete: "cascade" }),
  stepText: text("step_text").notNull(),
  stepDescription: text("step_description"),
  status: text("status").notNull().default("pending"), // pending, in-progress, completed
  dueDate: timestamp("due_date"),
  orderIndex: integer("order_index").notNull().default(0),
  createdAt: timestamp("created_at").notNull().defaultNow(),
  updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

// Notifications table
export const notifications = pgTable("notifications", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  userId: varchar("user_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  planId: varchar("plan_id").references(() => plans.id, {
    onDelete: "cascade",
  }),
  type: text("type").notNull(), // reminder, ai-suggestion
  message: text("message").notNull(),
  seen: boolean("seen").notNull().default(false),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

// AI logs table
export const aiLogs = pgTable("ai_logs", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  userId: varchar("user_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  planId: varchar("plan_id").references(() => plans.id, {
    onDelete: "cascade",
  }),
  prompt: text("prompt").notNull(),
  aiResponse: text("ai_response").notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

// Saved AI responses table
export const savedAiResponses = pgTable("saved_ai_responses", {
  id: varchar("id").primaryKey().default(sql`gen_random_uuid()`),
  userId: varchar("user_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  planId: varchar("plan_id")
    .notNull()
    .references(() => plans.id, { onDelete: "cascade" }),
  stepId: varchar("step_id").references(() => planSteps.id, {
    onDelete: "set null",
  }),
  stepName: text("step_name").notNull(),
  subject: text("subject").notNull(),
  userPrompt: text("user_prompt").notNull(),
  aiResponse: text("ai_response").notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

// Zod schemas for validation
export const upsertUserSchema = createInsertSchema(users).omit({
  createdAt: true,
  updatedAt: true,
  planLimit: true,
  isAdmin: true,
});

export const insertPlanSchema = createInsertSchema(plans).omit({
  id: true,
  createdAt: true,
  updatedAt: true,
  progressPercent: true,
});

export const insertStepSchema = createInsertSchema(planSteps).omit({
  id: true,
  createdAt: true,
  updatedAt: true,
});

export const insertNotificationSchema = createInsertSchema(notifications).omit(
  {
    id: true,
    createdAt: true,
  }
);

export const insertAiLogSchema = createInsertSchema(aiLogs).omit({
  id: true,
  createdAt: true,
});

export const insertSavedAiResponseSchema = createInsertSchema(savedAiResponses).omit({
  id: true,
  createdAt: true,
});

// Types
export type User = typeof users.$inferSelect;
export type UpsertUser = z.infer<typeof upsertUserSchema>;

export type Plan = typeof plans.$inferSelect;
export type InsertPlan = z.infer<typeof insertPlanSchema>;

export type PlanStep = typeof planSteps.$inferSelect;
export type InsertPlanStep = z.infer<typeof insertStepSchema>;

export type Notification = typeof notifications.$inferSelect;
export type InsertNotification = z.infer<typeof insertNotificationSchema>;

export type AiLog = typeof aiLogs.$inferSelect;
export type InsertAiLog = z.infer<typeof insertAiLogSchema>;

export type SavedAiResponse = typeof savedAiResponses.$inferSelect;
export type InsertSavedAiResponse = z.infer<typeof insertSavedAiResponseSchema>;
