// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

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

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

// User Management
model User {
  id            String   @id @default(cuid())
  email         String   @unique
  passwordHash  String
  firstName     String?
  lastName      String?
  avatar        String?
  isActive      Boolean  @default(true)
  emailVerified Boolean  @default(false)
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt

  // Subscription and billing
  subscription   SubscriptionTier @default(FREE)
  billingId      String?
  usageMetrics   UsageMetrics?
  
  // Relationships
  projects       Project[]
  collaborations ProjectCollaboration[]
  sessions       UserSession[]
  auditLogs      AuditLog[]

  @@map("users")
}

model UserSession {
  id        String   @id @default(cuid())
  userId    String
  token     String   @unique
  expiresAt DateTime
  createdAt DateTime @default(now())
  
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("user_sessions")
}

// Project Management
model Project {
  id          String        @id @default(cuid())
  name        String
  description String?
  sourceUrl   String
  status      ProjectStatus @default(CREATED)
  settings    Json          @default("{}")
  createdAt   DateTime      @default(now())
  updatedAt   DateTime      @updatedAt
  
  // Owner
  userId String
  user   User   @relation(fields: [userId], references: [id], onDelete: Cascade)
  
  // Relationships
  pages          Page[]
  assets         Asset[]
  components     Component[]
  collaborations ProjectCollaboration[]
  analytics      ProjectAnalytics?
  exports        ProjectExport[]

  @@map("projects")
}

model ProjectCollaboration {
  id        String           @id @default(cuid())
  projectId String
  userId    String
  role      CollaborationRole @default(VIEWER)
  createdAt DateTime         @default(now())
  
  project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  user    User    @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([projectId, userId])
  @@map("project_collaborations")
}

// Site Structure
model Page {
  id          String   @id @default(cuid())
  projectId   String
  url         String
  title       String?
  depth       Int      @default(0)
  status      PageStatus @default(DISCOVERED)
  metadata    Json     @default("{}")
  content     String?
  screenshot  String?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
  
  project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  assets  Asset[]
  
  @@unique([projectId, url])
  @@map("pages")
}

// Asset Management
model Asset {
  id           String    @id @default(cuid())
  projectId    String
  pageId       String?
  originalUrl  String
  storedUrl    String
  filename     String
  type         AssetType
  size         Int
  hash         String
  optimized    Boolean   @default(false)
  cdnUrl       String?
  metadata     Json      @default("{}")
  createdAt    DateTime  @default(now())
  
  project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  page    Page?   @relation(fields: [pageId], references: [id], onDelete: SetNull)

  @@unique([projectId, hash])
  @@map("assets")
}

// Component System
model Component {
  id          String        @id @default(cuid())
  projectId   String
  name        String
  type        ComponentType
  html        String
  css         String
  javascript  String?
  props       Json          @default("[]")
  frequency   Int           @default(1)
  createdAt   DateTime      @default(now())
  updatedAt   DateTime      @updatedAt
  
  project   Project           @relation(fields: [projectId], references: [id], onDelete: Cascade)
  instances ComponentInstance[]

  @@map("components")
}

model ComponentInstance {
  id          String   @id @default(cuid())
  componentId String
  selector    String
  props       Json     @default("{}")
  createdAt   DateTime @default(now())
  
  component Component @relation(fields: [componentId], references: [id], onDelete: Cascade)

  @@map("component_instances")
}

// Analytics and Metrics
model ProjectAnalytics {
  id               String   @id @default(cuid())
  projectId        String   @unique
  cloneAccuracy    Float?
  processingTime   Int?     // in milliseconds
  totalPages       Int      @default(0)
  totalAssets      Int      @default(0)
  totalComponents  Int      @default(0)
  lastUpdated      DateTime @default(now())
  
  project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  @@map("project_analytics")
}

model UsageMetrics {
  id            String   @id @default(cuid())
  userId        String   @unique
  pagesCloned   Int      @default(0)
  storageUsed   BigInt   @default(0) // in bytes
  apiCalls      Int      @default(0)
  lastReset     DateTime @default(now())
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
  
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("usage_metrics")
}

// Export and Deployment
model ProjectExport {
  id        String     @id @default(cuid())
  projectId String
  format    ExportFormat
  status    ExportStatus @default(PENDING)
  fileUrl   String?
  createdAt DateTime   @default(now())
  
  project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  @@map("project_exports")
}

// Security and Audit
model AuditLog {
  id        String   @id @default(cuid())
  userId    String?
  action    String
  resource  String
  details   Json     @default("{}")
  ipAddress String?
  userAgent String?
  createdAt DateTime @default(now())
  
  user User? @relation(fields: [userId], references: [id], onDelete: SetNull)

  @@map("audit_logs")
}

// Enums
enum SubscriptionTier {
  FREE
  BASIC
  PRO
  ENTERPRISE
}

enum ProjectStatus {
  CREATED
  CRAWLING
  PROCESSING
  GENERATING
  COMPLETED
  FAILED
}

enum PageStatus {
  DISCOVERED
  CRAWLING
  SCRAPED
  PROCESSED
  FAILED
}

enum AssetType {
  IMAGE
  CSS
  JAVASCRIPT
  FONT
  MEDIA
  OTHER
}

enum ComponentType {
  NAVIGATION
  HEADER
  FOOTER
  CARD
  FORM
  BUTTON
  OTHER
}

enum CollaborationRole {
  VIEWER
  EDITOR
  ADMIN
}

enum ExportFormat {
  ZIP
  GITHUB
  VERCEL
  NETLIFY
}

enum ExportStatus {
  PENDING
  PROCESSING
  COMPLETED
  FAILED
}