// ---------------------------------------------------------------------------
// DAR ZELLIGE — Prisma schema
// Portable schema: no enums, no Json, no arrays so it runs on SQLite (demo)
// and on PostgreSQL (production) with only the datasource provider changed.
// See README.md → "Switching to PostgreSQL".
// ---------------------------------------------------------------------------

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

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

// ------------------------------- Identity ---------------------------------

model User {
  id            String    @id @default(cuid())
  name          String
  email         String    @unique
  passwordHash  String
  phone         String?
  role          String    @default("CUSTOMER") // CUSTOMER | ADMIN (read-only demo) | SUPERADMIN
  emailVerified DateTime?
  image         String?
  createdAt     DateTime  @default(now())
  updatedAt     DateTime  @updatedAt

  addresses   CustomerAddress[]
  orders      Order[]
  carts       Cart[]
  wishlist    Wishlist?
  reviews     Review[]
  movements   InventoryMovement[]
  resetTokens PasswordResetToken[]

  @@index([role])
  @@index([createdAt])
}

model CustomerAddress {
  id           String   @id @default(cuid())
  userId       String
  label        String   @default("Domicile")
  fullName     String
  phone        String
  country      String   @default("MA")
  city         String
  addressLine1 String
  addressLine2 String?
  postalCode   String?
  isDefault    Boolean  @default(false)
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
}

model PasswordResetToken {
  id        String   @id @default(cuid())
  userId    String
  tokenHash String   @unique
  expiresAt DateTime
  usedAt    DateTime?
  createdAt DateTime @default(now())

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
}

// ------------------------------- Catalog ----------------------------------

model Category {
  id        String   @id @default(cuid())
  slug      String   @unique
  image     String
  position  Int      @default(0)
  isActive  Boolean  @default(true)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  translations CategoryTranslation[]
  products     Product[]

  @@index([position])
}

model CategoryTranslation {
  id          String @id @default(cuid())
  categoryId  String
  locale      String
  name        String
  description String

  category Category @relation(fields: [categoryId], references: [id], onDelete: Cascade)

  @@unique([categoryId, locale])
  @@index([locale])
}

model Product {
  id                String   @id @default(cuid())
  slug              String   @unique
  sku               String   @unique
  categoryId        String
  price             Int // centimes (MAD)
  compareAtPrice    Int? // centimes, original price when discounted
  costPrice         Int?
  stock             Int      @default(0)
  lowStockThreshold Int      @default(5)
  isPublished       Boolean  @default(true)
  isFeatured        Boolean  @default(false)
  rating            Float    @default(0)
  reviewCount       Int      @default(0)
  salesCount        Int      @default(0)
  createdAt         DateTime @default(now())
  updatedAt         DateTime @updatedAt

  category    Category            @relation(fields: [categoryId], references: [id], onDelete: Restrict)
  translations ProductTranslation[]
  images      ProductImage[]
  variants    ProductVariant[]
  cartItems   CartItem[]
  orderItems  OrderItem[]
  wishlistItems WishlistItem[]
  reviews     Review[]
  movements   InventoryMovement[]

  @@index([categoryId, isPublished])
  @@index([isFeatured, isPublished])
  @@index([createdAt])
  @@index([salesCount])
}

model ProductTranslation {
  id               String @id @default(cuid())
  productId        String
  locale           String
  name             String
  shortDescription String
  description      String
  materials        String
  dimensions       String
  origin           String
  artisanName      String
  artisanBio       String
  care             String

  product Product @relation(fields: [productId], references: [id], onDelete: Cascade)

  @@unique([productId, locale])
  @@index([locale])
}

model ProductImage {
  id        String @id @default(cuid())
  productId String
  url       String
  alt       String
  position  Int    @default(0)

  product Product @relation(fields: [productId], references: [id], onDelete: Cascade)

  @@index([productId, position])
}

model ProductVariant {
  id         String @id @default(cuid())
  productId  String
  sku        String @unique
  name       String
  priceDelta Int    @default(0) // centimes added to base price
  stock      Int    @default(0)
  position   Int    @default(0)

  product    Product    @relation(fields: [productId], references: [id], onDelete: Cascade)
  cartItems  CartItem[]
  orderItems OrderItem[]

  @@index([productId])
}

// --------------------------------- Cart -----------------------------------

model Cart {
  id         String   @id @default(cuid())
  token      String   @unique
  userId     String?
  couponCode String?
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  user  User?      @relation(fields: [userId], references: [id], onDelete: SetNull)
  items CartItem[]

  @@index([userId])
}

model CartItem {
  id        String   @id @default(cuid())
  cartId    String
  productId String
  variantId String?
  quantity  Int      @default(1)
  createdAt DateTime @default(now())

  cart    Cart            @relation(fields: [cartId], references: [id], onDelete: Cascade)
  product Product         @relation(fields: [productId], references: [id], onDelete: Cascade)
  variant ProductVariant? @relation(fields: [variantId], references: [id], onDelete: Cascade)

  @@unique([cartId, productId, variantId])
  @@index([cartId])
}

// --------------------------------- Orders ---------------------------------

model Order {
  id             String   @id @default(cuid())
  reference      String   @unique
  userId         String?
  status         String   @default("PENDING") // PENDING | CONFIRMED | PROCESSING | SHIPPED | DELIVERED | CANCELLED
  paymentMethod  String   @default("COD") // COD | BANK_TRANSFER | ONLINE
  paymentStatus  String   @default("PENDING") // PENDING | PAID | REFUNDED
  customerName   String
  email          String
  phone          String
  country        String
  city           String
  addressLine1   String
  addressLine2   String?
  postalCode     String?
  notes          String?
  subtotal       Int
  discount       Int      @default(0)
  shipping       Int      @default(0)
  total          Int
  currency       String   @default("MAD")
  locale         String   @default("fr")
  couponCode     String?
  adminNote      String?
  shippingCarrier String?
  trackingNumber String?
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt

  user  User?       @relation(fields: [userId], references: [id], onDelete: SetNull)
  items OrderItem[]

  @@index([status, createdAt])
  @@index([userId])
  @@index([email])
}

model OrderItem {
  id        String  @id @default(cuid())
  orderId   String
  productId String?
  variantId String?
  name      String
  variantName String?
  sku       String
  image     String?
  unitPrice Int
  quantity  Int
  total     Int

  order   Order           @relation(fields: [orderId], references: [id], onDelete: Cascade)
  product Product?        @relation(fields: [productId], references: [id], onDelete: SetNull)
  variant ProductVariant? @relation(fields: [variantId], references: [id], onDelete: SetNull)

  @@index([orderId])
  @@index([productId])
}

// -------------------------------- Wishlist ---------------------------------

model Wishlist {
  id        String   @id @default(cuid())
  userId    String   @unique
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  user  User           @relation(fields: [userId], references: [id], onDelete: Cascade)
  items WishlistItem[]
}

model WishlistItem {
  id         String   @id @default(cuid())
  wishlistId String
  productId  String
  createdAt  DateTime @default(now())

  wishlist Wishlist @relation(fields: [wishlistId], references: [id], onDelete: Cascade)
  product  Product  @relation(fields: [productId], references: [id], onDelete: Cascade)

  @@unique([wishlistId, productId])
  @@index([wishlistId])
}

// --------------------------------- Reviews ---------------------------------

model Review {
  id        String   @id @default(cuid())
  productId String
  userId    String?
  authorName String
  rating    Int
  title     String?
  comment   String
  isSample  Boolean  @default(true)
  createdAt DateTime @default(now())

  product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
  user    User?   @relation(fields: [userId], references: [id], onDelete: SetNull)

  @@index([productId, createdAt])
}

// -------------------------------- Marketing --------------------------------

model Coupon {
  id        String    @id @default(cuid())
  code      String    @unique
  type      String // PERCENT | FIXED
  value     Int // percentage (0-100) or centimes
  minOrder  Int       @default(0)
  maxUses   Int?
  usedCount Int       @default(0)
  startsAt  DateTime?
  expiresAt DateTime?
  isActive  Boolean   @default(true)
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt

  @@index([isActive])
}

model NewsletterSubscriber {
  id        String   @id @default(cuid())
  email     String   @unique
  locale    String   @default("fr")
  isActive  Boolean  @default(true)
  createdAt DateTime @default(now())
}

model ContactMessage {
  id        String   @id @default(cuid())
  name      String
  email     String
  subject   String
  message   String
  isRead    Boolean  @default(false)
  createdAt DateTime @default(now())

  @@index([createdAt])
}

// --------------------------------- Content ---------------------------------

model JournalArticle {
  id          String   @id @default(cuid())
  slug        String   @unique
  image       String
  author      String
  isPublished Boolean  @default(true)
  publishedAt DateTime @default(now())

  translations JournalArticleTranslation[]

  @@index([publishedAt])
}

model JournalArticleTranslation {
  id        String @id @default(cuid())
  articleId String
  locale    String
  title     String
  excerpt   String
  content   String

  article JournalArticle @relation(fields: [articleId], references: [id], onDelete: Cascade)

  @@unique([articleId, locale])
  @@index([locale])
}

model WebsiteSetting {
  id        String   @id @default(cuid())
  key       String   @unique
  value     String
  group     String   @default("general")
  updatedAt DateTime @updatedAt
}

// ------------------------------- Inventory ---------------------------------

model InventoryMovement {
  id            String   @id @default(cuid())
  productId     String
  variantId     String?
  type          String // SALE | RESTOCK | ADJUSTMENT | CANCELLATION
  quantity      Int // signed delta
  previousStock Int
  newStock      Int
  reason        String?
  orderId       String?
  userId        String?
  createdAt     DateTime @default(now())

  product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
  user    User?   @relation(fields: [userId], references: [id], onDelete: SetNull)

  @@index([productId, createdAt])
  @@index([createdAt])
}
