import { pgTable, text, serial, integer, boolean, timestamp, decimal, unique } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

export const users = pgTable("users", {
  id: serial("id").primaryKey(),
  firstName: text("first_name"),
  lastName: text("last_name"),
  showName: text("show_name"),
  email: text("email").notNull().unique(),
  roles: text("roles").notNull().default('["ROLE_USER"]'), // JSON array as text
  password: text("password").notNull(),
  active: boolean("active").notNull().default(true),
  home: integer("home"),
  phone: text("phone"),
  address: text("address"),
  town: text("town"),
  zipcode: integer("zipcode"),
  gender: text("gender"),
  age: text("age"),
  bio: text("bio"),
  avatar: text("avatar"),
  avatarBackgroundColor: text("avatar_background_color").default("#6366f1"), // Background color for avatar
  invitedBy: integer("invited_by").references(() => users.id),
  welcomeSequenceCompleted: boolean("welcome_sequence_completed").default(false),
  isImported: boolean("is_imported").default(false), // Track imported users
  registeredOn: timestamp("registered_on").defaultNow()
});

export const lendableItems = pgTable("lendable_items", {
  id: serial("id").primaryKey(),
  category: integer("category").notNull().references(() => lendableItemCategories.id),
  owner: integer("owner").notNull().references(() => users.id),
  name: text("name").notNull(),
  description: text("description"),
  specialInstructions: text("special_instructions"),
  condition: text("condition").default("good"),
  searchTerms: text("search_terms"),
  primaryLogo: text("primary_logo"),
  extraImages: text("extra_images"),
  pricePerDay: integer("price_per_day"),
  deposit: decimal("deposit", { precision: 8, scale: 2 }),
  status: boolean("status").notNull().default(true),
  isAvailable: boolean("is_available").notNull().default(true), // Owner can temporarily disable
  isRequest: boolean("is_request").notNull().default(false), // True for requests, false for items
  whenNeeded: text("when_needed"), // When the requester needs the item
  durationNeeded: text("duration_needed"), // How long they need it
  urgency: text("urgency"), // Low, medium, high, urgent
  requiresDigitalSignature: boolean("requires_digital_signature").default(false),
  ownerCanPushForward: boolean("owner_can_push_forward").default(true),
  workflowNotes: text("workflow_notes"),
  views: integer("views").default(0).notNull(), // Track view count
  addedOn: timestamp("added_on").notNull().defaultNow()
});



export const reviews = pgTable("reviews", {
  id: serial("id").primaryKey(),
  loanId: integer("loan_id").notNull().references(() => lendableLoanDetails.id),
  reviewerId: integer("reviewer_id").notNull().references(() => users.id),
  revieweeId: integer("reviewee_id").notNull().references(() => users.id),
  rating: integer("rating").notNull(),
  comment: text("comment"),
  createdAt: timestamp("created_at").defaultNow()
});

export const lendableItemCategories = pgTable("lendable_item_categories", {
  id: serial("id").primaryKey(),
  category: text("category").notNull(),
  description: text("description"),
  status: boolean("status").default(true).notNull()
});

export const userPreferences = pgTable("user_preferences", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").references(() => users.id).unique().notNull(),
  bio: text("bio"),
  skills: text("skills"),
  hobbies: text("hobbies"),
  displayPhone: boolean("display_phone").default(true).notNull(),
  smsNotifications: boolean("sms_notifications").default(false).notNull(),
  instantEmailNotifications: boolean("instant_email_notifications").default(false).notNull(),
  displayEmail: boolean("display_email").default(true).notNull(),
  displayAddress: boolean("display_address").default(true).notNull(),
  preferredPlaces: text("preferred_places"),
  displayFirstname: boolean("display_firstname").default(true).notNull(),
  displayLastname: boolean("display_lastname").default(true).notNull(),
  displayHome: boolean("display_home").default(true).notNull(),
  displayTown: boolean("display_town").default(true).notNull(),
  displayBio: boolean("display_bio").default(true).notNull(),
  displayGender: boolean("display_gender").default(true).notNull(),
  displayAge: boolean("display_age").default(true).notNull(),
  sendWeeklyEmail: boolean("send_weekly_email").default(true).notNull(),
  sendTripConfirmationEmail: boolean("send_trip_confirmation_email").default(true).notNull(),
  sendChatEmail: boolean("send_chat_email").default(true).notNull(),
  sendEventsEmail: boolean("send_events_email").default(true).notNull(),
  sendTripReminderEmail: boolean("send_trip_reminder_email").default(true).notNull(),
  onlyCommunity: boolean("only_community").default(true).notNull(),
  groups: text("groups"),
  personalLink: text("personal_link"),
  smsNumber: text("sms_number"),
});

export const lendableLoanDetails = pgTable("lendable_loan_details", {
  id: serial("id").primaryKey(),
  item: integer("item").references(() => lendableItems.id).notNull(),
  borrower: integer("borrower").references(() => users.id).notNull(),
  borrowedDate: timestamp("borrowed_date").notNull(),
  expectedReturnDate: timestamp("expected_return_date").notNull(),
  actualReturnDate: timestamp("actual_return_date"),
  borrowerComments: text("borrower_comments"),
  ownerComments: text("owner_comments"),
  addedOn: timestamp("added_on").defaultNow().notNull(),
  addedBy: integer("added_by").references(() => users.id).notNull(),
  type: text("type"),
  price: decimal("price", { precision: 8, scale: 2 }),
  ownerImages: text("owner_images"), // Comma-separated image paths
  borrowerImages: text("borrower_images"), // Comma-separated image paths
  providedToBorrower: boolean("provided_to_borrower").default(true).notNull(),
  returnedToOwner: boolean("returned_to_owner").default(false).notNull(),
});





// Borrow requests for specific items with date ranges
export const borrowRequests = pgTable("borrow_requests", {
  id: serial("id").primaryKey(),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  borrowerId: integer("borrower_id").notNull().references(() => users.id),
  ownerId: integer("owner_id").notNull().references(() => users.id),
  startDate: timestamp("start_date").notNull(),
  endDate: timestamp("end_date").notNull(),
  message: text("message"), // Optional message from borrower
  status: text("status").notNull().default("pending"), // pending, approved, rejected, expired, agreed
  createdAt: timestamp("created_at").defaultNow(),
  respondedAt: timestamp("responded_at"),
  expiresAt: timestamp("expires_at"), // Auto-expire if no response
  ownerResponse: text("owner_response"), // Owner's response message
  modifiedStartDate: timestamp("modified_start_date"), // Owner can modify dates
  modifiedEndDate: timestamp("modified_end_date"),
  agreementId: integer("agreement_id").references(() => loanAgreements.id)
});

// Digital loan agreements
export const loanAgreements = pgTable("loan_agreements", {
  id: serial("id").primaryKey(),
  borrowRequestId: integer("borrow_request_id").notNull().references(() => borrowRequests.id),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  borrowerId: integer("borrower_id").notNull().references(() => users.id),
  ownerId: integer("owner_id").notNull().references(() => users.id),
  startDate: timestamp("start_date").notNull(),
  endDate: timestamp("end_date").notNull(),
  agreementTerms: text("agreement_terms").notNull(), // Legal terms
  dailyRate: decimal("daily_rate", { precision: 8, scale: 2 }),
  totalAmount: decimal("total_amount", { precision: 8, scale: 2 }),
  borrowerSignedAt: timestamp("borrower_signed_at"),
  ownerSignedAt: timestamp("owner_signed_at"),
  borrowerSignature: text("borrower_signature"), // Digital signature data
  ownerSignature: text("owner_signature"),
  status: text("status").notNull().default("pending"), // pending, signed, active, completed, cancelled
  createdAt: timestamp("created_at").defaultNow(),
  returnQrCode: text("return_qr_code"), // QR code for return process
  returnInstructions: text("return_instructions")
});

// CONSOLIDATED LOAN SYSTEM - Unified loan transaction tracking
export const loanTransactions = pgTable("loan_transactions", {
  id: serial("id").primaryKey(),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  borrowerId: integer("borrower_id").notNull().references(() => users.id),
  ownerId: integer("owner_id").notNull().references(() => users.id),
  agreementId: integer("agreement_id").references(() => loanAgreements.id),
  
  // Unified workflow status covering all loan stages
  status: text("status").notNull().default("pending"), // pending, approved, active, return_requested, returned, rejected, cancelled
  
  // Complete timeline tracking
  requestedDate: timestamp("requested_date").defaultNow(),
  approvedDate: timestamp("approved_date"),
  borrowedDate: timestamp("borrowed_date"),
  expectedReturnDate: timestamp("expected_return_date"),
  pickedUpAt: timestamp("picked_up_at"),
  returnRequestedAt: timestamp("return_requested_at"),
  returnedAt: timestamp("returned_at"),
  
  // Communication & details
  message: text("message"), // Initial request message
  ownerResponse: text("owner_response"), // Owner's response
  returnCondition: text("return_condition"), // good, damaged, missing
  returnNotes: text("return_notes"),
  
  // Financial details
  dailyRate: decimal("daily_rate", { precision: 8, scale: 2 }),
  totalAmount: decimal("total_amount", { precision: 8, scale: 2 }),
  
  // Source tracking for migration
  sourceSystem: text("source_system"), // 'borrow_requests', 'active_loan_tracking', 'lendable_loan_details'
  originalId: integer("original_id"), // Original ID from source system
  
  // Metadata
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow()
});

// LEGACY TABLES - Keep for data integrity during transition
// Enhanced loan tracking
export const activeLoanTracking = pgTable("active_loan_tracking", {
  id: serial("id").primaryKey(),
  agreementId: integer("agreement_id").notNull().references(() => loanAgreements.id),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  borrowerId: integer("borrower_id").notNull().references(() => users.id),
  ownerId: integer("owner_id").notNull().references(() => users.id),
  status: text("status").notNull().default("reserved"), // reserved, active, returned, overdue
  pickedUpAt: timestamp("picked_up_at"),
  returnRequestedAt: timestamp("return_requested_at"),
  returnedAt: timestamp("returned_at"),
  returnCondition: text("return_condition"), // good, damaged, missing
  returnNotes: text("return_notes"),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow()
});

// Admin-editable legal language with versioning
export const legalContent = pgTable("legal_content", {
  id: serial("id").primaryKey(),
  type: text("type").notNull(), // borrower_terms, owner_terms, general_terms
  title: text("title").notNull(),
  content: text("content").notNull(),
  version: integer("version").default(1).notNull(),
  isActive: boolean("is_active").default(true).notNull(),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow(),
  createdBy: integer("created_by").references(() => users.id)
});

export const staticPages = pgTable("static_pages", {
  id: serial("id").primaryKey(),
  slug: text("slug").notNull().unique(), // URL-friendly identifier
  title: text("title").notNull(),
  content: text("content").notNull(), // HTML content with variable placeholders
  variables: text("variables"), // JSON object of available variables for this page
  isActive: boolean("is_active").notNull().default(true),
  sortOrder: integer("sort_order").default(0),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow(),
  createdBy: integer("created_by").notNull().references(() => users.id),
  updatedBy: integer("updated_by").notNull().references(() => users.id)
});

export const hourOfferings = pgTable("hour_offerings", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  title: text("title").notNull(), // e.g., "Moving help", "Handyman assistance"
  description: text("description"), // What kind of help being offered
  offerDate: timestamp("offer_date").notNull(), // Specific date and start time
  endTime: timestamp("end_time").notNull(), // When the available window ends
  isActive: boolean("is_active").notNull().default(true),
  isBooked: boolean("is_booked").notNull().default(false),
  isRecurring: boolean("is_recurring").notNull().default(false),
  recurringType: text("recurring_type"), // "weekly", "biweekly", "monthly"
  recurringCount: integer("recurring_count"), // Number of times to repeat (4-20)
  recurringEndDate: timestamp("recurring_end_date"), // When recurring series ends
  parentOfferingId: integer("parent_offering_id"), // Reference to original offering for recurring series
  createdAt: timestamp("created_at").defaultNow()
});

// Content Management System for editable text blocks
export const contentBlocks = pgTable("content_blocks", {
  id: serial("id").primaryKey(),
  identifier: text("identifier").notNull().unique(), // Unique key like "privacy_notice_edit_profile"
  title: text("title").notNull(), // Human-readable title
  content: text("content").notNull(), // The actual content
  contentType: text("content_type").notNull().default("text"), // text, html, markdown
  parentPage: text("parent_page").notNull(), // Page where this content appears
  section: text("section"), // Optional section within the page
  editPermission: text("edit_permission").notNull().default("admin"), // admin, manager, owner
  isActive: boolean("is_active").default(true).notNull(),
  sortOrder: integer("sort_order").default(0),
  version: integer("version").default(1).notNull(),
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow(),
  createdBy: integer("created_by").references(() => users.id),
  updatedBy: integer("updated_by").references(() => users.id)
});

// Content block edit history for tracking changes
export const contentBlockHistory = pgTable("content_block_history", {
  id: serial("id").primaryKey(),
  contentBlockId: integer("content_block_id").notNull().references(() => contentBlocks.id),
  previousContent: text("previous_content").notNull(),
  newContent: text("new_content").notNull(),
  changeReason: text("change_reason"), // Optional reason for the change
  version: integer("version").notNull(),
  editedBy: integer("edited_by").notNull().references(() => users.id),
  editedAt: timestamp("edited_at").defaultNow()
});

// In-app notifications
export const notifications = pgTable("notifications", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  type: text("type").notNull(), // borrow_request, request_approved, request_rejected, etc.
  title: text("title").notNull(),
  message: text("message").notNull(),
  relatedId: integer("related_id"), // ID of related borrow request, item, etc.
  relatedType: text("related_type"), // borrow_request, item, etc.
  itemId: integer("item_id").references(() => lendableItems.id),
  isRead: boolean("is_read").default(false).notNull(),
  isDismissed: boolean("is_dismissed").default(false).notNull(),
  createdAt: timestamp("created_at").defaultNow()
});

// Chat conversations between users about specific items
export const conversations = pgTable("conversations", {
  id: serial("id").primaryKey(),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  ownerId: integer("owner_id").notNull().references(() => users.id),
  borrowerId: integer("borrower_id").notNull().references(() => users.id),
  status: text("status").default("active").notNull(), // active, archived
  lastMessageAt: timestamp("last_message_at").defaultNow(),
  createdAt: timestamp("created_at").defaultNow()
});

// Chat messages with audio support and transcription
export const chatMessages = pgTable("chat_messages", {
  id: serial("id").primaryKey(),
  conversationId: integer("conversation_id").notNull().references(() => conversations.id),
  senderId: integer("sender_id").notNull().references(() => users.id),
  messageType: text("message_type").notNull().default("text"), // text, audio
  textContent: text("text_content"),
  audioPath: text("audio_path"),
  transcription: text("transcription"), // Machine transcription from Whisper
  isRead: boolean("is_read").default(false).notNull(),
  isActive: boolean("is_active").default(true).notNull(), // Admin can deactivate messages
  createdAt: timestamp("created_at").defaultNow()
});

// Member activity log
export const memberActivity = pgTable("member_activity", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  activityType: text("activity_type").notNull(), // item_added, item_borrowed, message_sent, etc.
  description: text("description").notNull(),
  relatedItemId: integer("related_item_id"), // Optional reference to item
  relatedMessageId: integer("related_message_id"), // Optional reference to message
  isActive: boolean("is_active").default(true).notNull(), // Admin can deactivate activities
  createdAt: timestamp("created_at").defaultNow()
});

// User favorites for items
export const userFavorites = pgTable("user_favorites", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  itemId: integer("item_id").notNull().references(() => lendableItems.id),
  createdAt: timestamp("created_at").defaultNow()
}, (table) => ({
  // Ensure a user can only favorite an item once
  uniqueFavorite: unique("unique_user_item_favorite").on(table.userId, table.itemId)
}));

// Email notification system settings
export const emailNotificationSettings = pgTable("email_notification_settings", {
  id: serial("id").primaryKey(),
  isEnabled: boolean("is_enabled").default(true),
  temporaryMode: boolean("temporary_mode").default(true), // Routes all emails to manager during development
  temporaryEmail: text("temporary_email").default("manager@tatacommons.com"),
  dailyScheduleTime: text("daily_schedule_time").default("09:00"), // 24-hour format
  timezone: text("timezone").default("America/Halifax"),
  lastRunDate: text("last_run_date"), // YYYY-MM-DD format
  isRunning: boolean("is_running").default(false), // Prevent concurrent runs
  createdAt: timestamp("created_at").defaultNow(),
  updatedAt: timestamp("updated_at").defaultNow()
});

// Email delivery log
export const emailNotificationLog = pgTable("email_notification_log", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  recipientEmail: text("recipient_email").notNull(),
  subject: text("subject").notNull(),
  messageCount: integer("message_count").default(0),
  notificationCount: integer("notification_count").default(0),
  status: text("status").notNull(), // 'sent', 'failed', 'skipped'
  errorMessage: text("error_message"),
  sendgridMessageId: text("sendgrid_message_id"),
  sentAt: timestamp("sent_at").defaultNow()
});

// Daily digest queue for processing
export const emailDigestQueue = pgTable("email_digest_queue", {
  id: serial("id").primaryKey(),
  userId: integer("user_id").notNull().references(() => users.id),
  userName: text("user_name").notNull(),
  userEmail: text("user_email").notNull(),
  hasNewMessages: boolean("has_new_messages").default(false),
  hasNewNotifications: boolean("has_new_notifications").default(false),
  messageCount: integer("message_count").default(0),
  notificationCount: integer("notification_count").default(0),
  lastMessageDate: timestamp("last_message_date"),
  lastNotificationDate: timestamp("last_notification_date"),
  queuedAt: timestamp("queued_at").defaultNow(),
  processedAt: timestamp("processed_at"),
  status: text("status").default("pending") // 'pending', 'processing', 'sent', 'failed', 'skipped'
});

// Relations
export const usersRelations = relations(users, ({ many, one }) => ({
  reviewsGiven: many(reviews, { relationName: "reviewer" }),
  reviewsReceived: many(reviews, { relationName: "reviewee" }),
  preferences: one(userPreferences, {
    fields: [users.id],
    references: [userPreferences.userId]
  }),
  favorites: many(userFavorites)
}));



export const lendableItemsRelations = relations(lendableItems, ({ one, many }) => ({
  category: one(lendableItemCategories, {
    fields: [lendableItems.category],
    references: [lendableItemCategories.id]
  }),
  owner: one(users, {
    fields: [lendableItems.owner],
    references: [users.id]
  }),
  favorites: many(userFavorites)
}));

export const lendableItemCategoriesRelations = relations(lendableItemCategories, ({ many }) => ({
  lendableItems: many(lendableItems)
}));

export const reviewsRelations = relations(reviews, ({ one }) => ({
  loan: one(lendableLoanDetails, {
    fields: [reviews.loanId],
    references: [lendableLoanDetails.id]
  }),
  reviewer: one(users, {
    fields: [reviews.reviewerId],
    references: [users.id],
    relationName: "reviewer"
  }),
  reviewee: one(users, {
    fields: [reviews.revieweeId],
    references: [users.id],
    relationName: "reviewee"
  })
}));

export const userPreferencesRelations = relations(userPreferences, ({ one }) => ({
  user: one(users, {
    fields: [userPreferences.userId],
    references: [users.id]
  })
}));

export const loanTransactionsRelations = relations(loanTransactions, ({ one }) => ({
  item: one(lendableItems, {
    fields: [loanTransactions.itemId],
    references: [lendableItems.id]
  }),
  borrower: one(users, {
    fields: [loanTransactions.borrowerId],
    references: [users.id],
    relationName: "loanTransactionsBorrower"
  }),
  owner: one(users, {
    fields: [loanTransactions.ownerId],
    references: [users.id],
    relationName: "loanTransactionsOwner"
  }),
  agreement: one(loanAgreements, {
    fields: [loanTransactions.agreementId],
    references: [loanAgreements.id]
  })
}));

export const borrowRequestsRelations = relations(borrowRequests, ({ one }) => ({
  item: one(lendableItems, {
    fields: [borrowRequests.itemId],
    references: [lendableItems.id]
  }),
  borrower: one(users, {
    fields: [borrowRequests.borrowerId],
    references: [users.id],
    relationName: "borrowRequestsBorrower"
  }),
  owner: one(users, {
    fields: [borrowRequests.ownerId],
    references: [users.id],
    relationName: "borrowRequestsOwner"
  })
}));

export const notificationsRelations = relations(notifications, ({ one }) => ({
  user: one(users, {
    fields: [notifications.userId],
    references: [users.id]
  })
}));

export const userFavoritesRelations = relations(userFavorites, ({ one }) => ({
  user: one(users, {
    fields: [userFavorites.userId],
    references: [users.id]
  }),
  item: one(lendableItems, {
    fields: [userFavorites.itemId],
    references: [lendableItems.id]
  })
}));

export const conversationsRelations = relations(conversations, ({ one, many }) => ({
  item: one(lendableItems, {
    fields: [conversations.itemId],
    references: [lendableItems.id]
  }),
  owner: one(users, {
    fields: [conversations.ownerId],
    references: [users.id],
    relationName: "conversationOwner"
  }),
  borrower: one(users, {
    fields: [conversations.borrowerId],
    references: [users.id],
    relationName: "conversationBorrower"
  }),
  messages: many(chatMessages)
}));

export const contentBlocksRelations = relations(contentBlocks, ({ one, many }) => ({
  creator: one(users, {
    fields: [contentBlocks.createdBy],
    references: [users.id],
    relationName: "contentBlockCreator"
  }),
  updater: one(users, {
    fields: [contentBlocks.updatedBy],
    references: [users.id],
    relationName: "contentBlockUpdater"
  }),
  history: many(contentBlockHistory)
}));

export const contentBlockHistoryRelations = relations(contentBlockHistory, ({ one }) => ({
  contentBlock: one(contentBlocks, {
    fields: [contentBlockHistory.contentBlockId],
    references: [contentBlocks.id]
  }),
  editor: one(users, {
    fields: [contentBlockHistory.editedBy],
    references: [users.id]
  })
}));

export const chatMessagesRelations = relations(chatMessages, ({ one }) => ({
  conversation: one(conversations, {
    fields: [chatMessages.conversationId],
    references: [conversations.id]
  }),
  sender: one(users, {
    fields: [chatMessages.senderId],
    references: [users.id]
  })
}));

export const hourOfferingsRelations = relations(hourOfferings, ({ one }) => ({
  user: one(users, {
    fields: [hourOfferings.userId],
    references: [users.id]
  })
}));

// Simplified schemas for basic validation
export const insertUserSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
  firstName: z.string().optional(),
  lastName: z.string().optional()
});

export const insertLendableItemSchema = z.object({
  owner: z.number(),
  name: z.string().min(1),
  description: z.string().optional(),
  category: z.number(),
  primaryLogo: z.string().optional(),
  extraImages: z.string().optional(),
  pricePerDay: z.number().optional()
});

export const insertBorrowRequestSchema = z.object({
  itemId: z.number(),
  borrowerId: z.number(),
  ownerId: z.number(),
  startDate: z.date(),
  endDate: z.date(),
  message: z.string().optional()
});

export const insertConversationSchema = z.object({
  itemId: z.number(),
  ownerId: z.number(),
  borrowerId: z.number(),
  status: z.string().optional()
});

export const insertChatMessageSchema = z.object({
  conversationId: z.number(),
  senderId: z.number(),
  messageType: z.string().optional(),
  textContent: z.string().optional(),
  audioPath: z.string().optional(),
  transcription: z.string().optional()
});

export type User = typeof users.$inferSelect;
export type LendableItem = typeof lendableItems.$inferSelect;
export type LendableItemCategory = typeof lendableItemCategories.$inferSelect;
export type BorrowRequest = typeof borrowRequests.$inferSelect;
export type LoanTransaction = typeof loanTransactions.$inferSelect;
export type LegalContent = typeof legalContent.$inferSelect;

export type Notification = typeof notifications.$inferSelect;

export const insertStaticPageSchema = createInsertSchema(staticPages);
export type InsertStaticPage = z.infer<typeof insertStaticPageSchema>;
export type SelectStaticPage = typeof staticPages.$inferSelect;
export type Conversation = typeof conversations.$inferSelect;
export type ChatMessage = typeof chatMessages.$inferSelect;

// Insert types using manual definitions to avoid Zod compilation issues
export type InsertUser = {
  email: string;
  password: string;
  firstName?: string;
  lastName?: string;
};

export type InsertLendableItem = {
  owner: number;
  name: string;
  description?: string;
  category: number;
  primaryLogo?: string;
  extraImages?: string;
  pricePerDay?: number;
};

export type InsertLendableItemCategory = {
  category: string;
  description?: string;
};

export type InsertBorrowRequest = {
  itemId: number;
  borrowerId: number;
  ownerId: number;
  startDate: Date;
  endDate: Date;
  message?: string;
};

export type InsertConversation = {
  itemId: number;
  ownerId: number;
  borrowerId: number;
  status?: string;
};

export type InsertChatMessage = {
  conversationId: number;
  senderId: number;
  messageType?: string;
  textContent?: string;
  audioPath?: string;
  transcription?: string;
};

// Hour offerings schema and types
export const insertHourOfferingSchema = z.object({
  userId: z.number(),
  title: z.string().min(1),
  description: z.string().optional(),
  offerDate: z.date(),
  endTime: z.date(),
  isRecurring: z.boolean().optional().default(false),
  recurringType: z.string().optional(),
  recurringCount: z.number().min(2).max(20).optional(),
  parentOfferingId: z.number().optional()
});

export type HourOffering = typeof hourOfferings.$inferSelect;
export type InsertHourOffering = z.infer<typeof insertHourOfferingSchema>;

// Email notification system types
export type EmailNotificationSettings = typeof emailNotificationSettings.$inferSelect;
export type InsertEmailNotificationSettings = z.infer<typeof insertEmailNotificationSettingsSchema>;
export type EmailNotificationLog = typeof emailNotificationLog.$inferSelect;
export type InsertEmailNotificationLog = z.infer<typeof insertEmailNotificationLogSchema>;
export type EmailDigestQueue = typeof emailDigestQueue.$inferSelect;
export type InsertEmailDigestQueue = z.infer<typeof insertEmailDigestQueueSchema>;

// Email notification schemas
export const insertEmailNotificationSettingsSchema = createInsertSchema(emailNotificationSettings);
export const insertEmailNotificationLogSchema = createInsertSchema(emailNotificationLog);
export const insertEmailDigestQueueSchema = createInsertSchema(emailDigestQueue);
