generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id                String              @id @default(cuid())
  email             String              @unique
  name              String?
  createdAt         DateTime            @default(now())
  updatedAt         DateTime            @updatedAt
  apiKeys           ApiKey[]
  trades            Trade[]
  journals          TradingJournal[]
  settings          UserSettings?
  automationSessions AutomationSession[]
  aiLearningData    AILearningData[]

  @@map("users")
}

model ApiKey {
  id           String   @id @default(cuid())
  userId       String
  provider     String
  keyName      String
  encryptedKey String
  isActive     Boolean  @default(true)
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([userId, provider, keyName])
  @@map("api_keys")
}

model UserSettings {
  id                  String   @id @default(cuid())
  userId              String   @unique
  autoTrading         Boolean  @default(false)
  tradingAmount       Float    @default(100)
  riskPercentage      Float    @default(2)
  maxDailyTrades      Int      @default(5)
  enableNotifications Boolean  @default(true)
  // Automation settings
  automationMode      String   @default("SIMULATION") // SIMULATION, LIVE
  autoTimeframe       String   @default("1h")
  autoSymbol          String   @default("SOLUSD")
  autoTradingEnabled  Boolean  @default(false)
  autoAnalysisEnabled Boolean  @default(false)
  maxLeverage         Float    @default(3.0)
  stopLossPercent     Float    @default(2.0)
  takeProfitPercent   Float    @default(6.0)
  createdAt           DateTime @default(now())
  updatedAt           DateTime @updatedAt
  user                User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("user_settings")
}

model Trade {
  id            String    @id @default(cuid())
  userId        String
  symbol        String
  side          String
  amount        Float
  price         Float
  status        String    @default("PENDING")
  driftTxId     String?
  profit        Float?
  fees          Float?
  screenshotUrl String?
  aiAnalysis    String?
  // Automation fields
  isAutomated   Boolean   @default(false)
  entryPrice    Float?
  exitPrice     Float?
  stopLoss      Float?
  takeProfit    Float?
  leverage      Float?
  timeframe     String?
  tradingMode   String?   // SIMULATION, LIVE
  confidence    Float?
  marketSentiment String?
  // Learning fields
  outcome       String?   // WIN, LOSS, BREAKEVEN
  pnlPercent    Float?
  actualRR      Float?    // Actual risk/reward ratio
  executionTime DateTime?
  learningData  Json?     // Store additional learning data
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt
  executedAt    DateTime?
  closedAt      DateTime?
  user          User      @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("trades")
}

model TradingJournal {
  id              String   @id @default(cuid())
  userId          String
  date            DateTime @default(now())
  screenshotUrl   String
  aiAnalysis      String
  marketSentiment String?
  keyLevels       Json?
  recommendation  String
  confidence      Float
  notes           String?
  // Automation fields
  isAutomated     Boolean  @default(false)
  symbol          String?
  timeframe       String?
  tradingMode     String?  // SIMULATION, LIVE
  tradeId         String?  // Link to actual trade if executed
  outcome         String?  // WIN, LOSS, BREAKEVEN, PENDING
  actualPrice     Float?   // Actual price when trade was executed
  priceAtAnalysis Float?   // Price at time of analysis
  // Learning fields  
  accuracyScore   Float?   // How accurate the prediction was
  executionDelay  Int?     // Minutes between analysis and execution
  marketCondition String?  // TRENDING, RANGING, VOLATILE
  sessionId       String?  // Link to automation session
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  user            User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("trading_journals")
}

model Screenshot {
  id        String   @id @default(cuid())
  url       String
  filename  String
  fileSize  Int
  mimeType  String
  metadata  Json?
  createdAt DateTime @default(now())

  @@map("screenshots")
}

model SystemLog {
  id        String   @id @default(cuid())
  level     String
  message   String
  metadata  Json?
  createdAt DateTime @default(now())

  @@map("system_logs")
}

model AutomationSession {
  id              String   @id @default(cuid())
  userId          String
  status          String   @default("ACTIVE") // ACTIVE, PAUSED, STOPPED
  mode            String   @default("SIMULATION") // SIMULATION, LIVE
  symbol          String
  timeframe       String
  totalTrades     Int      @default(0)
  successfulTrades Int     @default(0)
  failedTrades    Int      @default(0)
  totalPnL        Float    @default(0)
  totalPnLPercent Float    @default(0)
  winRate         Float    @default(0)
  avgRiskReward   Float    @default(0)
  maxDrawdown     Float    @default(0)
  startBalance    Float?
  currentBalance  Float?
  settings        Json?    // Store automation settings
  lastAnalysis    DateTime?
  lastTrade       DateTime?
  nextScheduled   DateTime?
  errorCount      Int      @default(0)
  lastError       String?
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  user            User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([userId, symbol, timeframe])
  @@map("automation_sessions")
}

model AILearningData {
  id                String   @id @default(cuid())
  userId            String
  sessionId         String?
  tradeId           String?
  analysisData      Json     // Store the AI analysis
  marketConditions  Json     // Store market conditions at time of analysis
  outcome           String?  // WIN, LOSS, BREAKEVEN
  actualPrice       Float?
  predictedPrice    Float?
  confidenceScore   Float?
  accuracyScore     Float?   // Calculated after outcome is known
  timeframe         String
  symbol            String
  screenshot        String?  // Link to screenshot used for analysis
  feedbackData      Json?    // Store feedback for learning
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt
  user              User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("ai_learning_data")
}
