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

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

// ========================
// User & Auth
// ========================
model User {
  id                   Int       @id @default(autoincrement())
  email                String    @unique @db.VarChar(255)
  passwordHash         String    @map("password_hash") @db.VarChar(255)
  name                 String    @db.VarChar(100)
  nameEn               String?   @map("name_en") @db.VarChar(100)
  phone                String?   @db.VarChar(20)
  avatarUrl            String?   @map("avatar_url") @db.VarChar(500)
  languagePreference   String    @default("ko") @map("language_preference") @db.VarChar(5)
  emailVerified        Boolean   @default(false) @map("email_verified")
  emailVerifyToken     String?   @map("email_verify_token") @db.VarChar(255)
  passwordResetToken   String?   @map("password_reset_token") @db.VarChar(255)
  passwordResetExpires DateTime? @map("password_reset_expires")
  refreshToken         String?   @map("refresh_token") @db.VarChar(500)
  isActive             Boolean   @default(true) @map("is_active")
  createdAt            DateTime  @default(now()) @map("created_at")
  updatedAt            DateTime  @updatedAt @map("updated_at")

  business             Business?
  notificationSettings NotificationSettings?
  clients              Client[]
  projects             Project[]
  estimates            Estimate[]
  contracts            Contract[]
  taxInvoices          TaxInvoice[]
  cashReceipts         CashReceipt[]
  settlements          Settlement[]
  purchaseSaleRecords  PurchaseSaleRecord[]
  expenseCategories    ExpenseCategory[]
  expenses             Expense[]
  fixedExpenses        FixedExpense[]
  templates            Template[]
  aiConversations      AiConversation[]
  subscription         Subscription?
  addonSubscriptions   AddonSubscription[]
  billingHistory       BillingHistory[]
  creditSettings       CreditSettings?
  creditTransactions   CreditTransaction[]
  paymentMethods       PaymentMethod[]
  linkedAccounts       LinkedAccount[]
  notifications        Notification[]

  @@map("users")
}

model NotificationSettings {
  id                Int       @id @default(autoincrement())
  userId            Int       @unique @map("user_id")
  emailEnabled      Boolean   @default(true) @map("email_enabled")
  pushEnabled       Boolean   @default(false) @map("push_enabled")
  smsEnabled        Boolean   @default(false) @map("sms_enabled")
  settlementAlerts  Boolean   @default(true) @map("settlement_alerts")
  documentAlerts    Boolean   @default(true) @map("document_alerts")
  taxAlerts         Boolean   @default(true) @map("tax_alerts")
  marketingEmails   Boolean   @default(false) @map("marketing_emails")
  fcmToken          String?   @map("fcm_token") @db.VarChar(500)
  fcmTokenUpdatedAt DateTime? @map("fcm_token_updated_at")

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

  @@map("notification_settings")
}


// ========================
// Business
// ========================
model Business {
  id                    Int       @id @default(autoincrement())
  userId                Int       @unique @map("user_id")
  businessName          String    @map("business_name") @db.VarChar(200)
  businessNameEn        String?   @map("business_name_en") @db.VarChar(200)
  registrationNumber    String?   @map("registration_number") @db.VarChar(20)
  ownerName             String?   @map("owner_name") @db.VarChar(100)
  ownerNameEn           String?   @map("owner_name_en") @db.VarChar(100)
  businessType          String?   @map("business_type") @db.VarChar(100)
  businessTypeEn        String?   @map("business_type_en") @db.VarChar(100)
  businessItem          String?   @map("business_item") @db.VarChar(200)
  businessItemEn        String?   @map("business_item_en") @db.VarChar(200)
  address               String?   @db.VarChar(500)
  addressEn             String?   @map("address_en") @db.VarChar(500)
  phone                 String?   @db.VarChar(20)
  email                 String?   @db.VarChar(255)
  taxType               String    @default("general") @map("tax_type") @db.VarChar(20)
  taxRate               Int       @default(20) @map("tax_rate")
  calculationBasis      String    @default("revenue") @map("calculation_basis") @db.VarChar(20)
  registrationCertUrl   String?   @map("registration_cert_url") @db.VarChar(500)
  digitalCertRegistered Boolean   @default(false) @map("digital_cert_registered")
  digitalCertValidFrom  DateTime? @map("digital_cert_valid_from")
  digitalCertValidUntil DateTime? @map("digital_cert_valid_until")
  hometaxAuthStatus     String    @default("unregistered") @map("hometax_auth_status") @db.VarChar(20)
  hometaxAuthMethod     String?   @map("hometax_auth_method") @db.VarChar(10)
  hometaxAuthRegisteredAt DateTime? @map("hometax_auth_registered_at")
  createdAt             DateTime  @default(now()) @map("created_at")
  updatedAt             DateTime  @updatedAt @map("updated_at")

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

  @@map("businesses")
}

// ========================
// Client
// ========================
model Client {
  id                 Int       @id @default(autoincrement())
  userId             Int       @map("user_id")
  name               String    @db.VarChar(200)
  nameEn             String?   @map("name_en") @db.VarChar(200)
  email              String?   @db.VarChar(255)
  phone              String?   @db.VarChar(30)
  registrationNumber String?   @map("registration_number") @db.VarChar(20)
  representative     String?   @db.VarChar(100)
  address            String?   @db.VarChar(500)
  addressEn          String?   @map("address_en") @db.VarChar(500)
  businessType       String?   @map("business_type") @db.VarChar(100)
  businessItem       String?   @map("business_item") @db.VarChar(100)
  contactPerson      String?   @map("contact_person") @db.VarChar(100)
  contactPhone       String?   @map("contact_phone") @db.VarChar(30)
  notes              String?   @db.Text
  createdAt          DateTime  @default(now()) @map("created_at")
  updatedAt          DateTime  @updatedAt @map("updated_at")

  user               User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  projects           Project[]
  estimates          Estimate[]
  contracts          Contract[]
  taxInvoices        TaxInvoice[]
  settlements        Settlement[]

  @@index([userId])
  @@map("clients")
}

// ========================
// Project
// ========================
model Project {
  id          Int       @id @default(autoincrement())
  userId      Int       @map("user_id")
  clientId    Int?      @map("client_id")
  name        String    @db.VarChar(300)
  nameEn      String?   @map("name_en") @db.VarChar(300)
  status      String    @default("estimate-in-progress") @db.VarChar(30)
  value       BigInt    @default(0)
  startDate   DateTime? @map("start_date") @db.Date
  endDate     DateTime? @map("end_date") @db.Date
  description String?   @db.Text
  createdAt   DateTime  @default(now()) @map("created_at")
  updatedAt   DateTime  @updatedAt @map("updated_at")

  user        User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  client      Client?   @relation(fields: [clientId], references: [id], onDelete: SetNull)
  estimates          Estimate[]
  contracts          Contract[]
  taxInvoices        TaxInvoice[]
  settlements        Settlement[]
  purchaseSaleRecords PurchaseSaleRecord[]

  @@index([userId])
  @@index([status])
  @@map("projects")
}

// ========================
// Estimate
// ========================
model Estimate {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  projectId       Int?      @map("project_id")
  clientId        Int?      @map("client_id")
  clientName      String?   @map("client_name") @db.VarChar(200)
  projectName     String?   @map("project_name") @db.VarChar(200)
  estimateNumber  String    @map("estimate_number") @db.VarChar(30)
  status          String    @default("draft") @db.VarChar(20)
  issueDate       DateTime  @map("issue_date") @db.Date
  validDays       Int       @default(30) @map("valid_days")
  subtotal        BigInt    @default(0)
  taxAmount       BigInt    @default(0) @map("tax_amount")
  totalAmount     BigInt    @default(0) @map("total_amount")
  memo            String?   @db.Text
  templateId      Int?      @map("template_id")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

  user            User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  project         Project?  @relation(fields: [projectId], references: [id], onDelete: SetNull)
  client          Client?   @relation(fields: [clientId], references: [id], onDelete: SetNull)
  items           EstimateItem[]
  contracts       Contract[]

  @@index([userId, status])
  @@map("estimates")
}

model EstimateItem {
  id          Int     @id @default(autoincrement())
  estimateId  Int     @map("estimate_id")
  description String  @db.VarChar(500)
  category    String? @db.VarChar(200)
  quantity    Int     @default(1)
  unitPrice   BigInt  @default(0) @map("unit_price")
  amount      BigInt  @default(0)
  note        String? @db.VarChar(500)
  sortOrder   Int     @default(0) @map("sort_order")

  estimate    Estimate @relation(fields: [estimateId], references: [id], onDelete: Cascade)

  @@map("estimate_items")
}

// ========================
// Contract
// ========================
model Contract {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  projectId       Int?      @map("project_id")
  clientId        Int?      @map("client_id")
  estimateId      Int?      @map("estimate_id")
  clientName      String?   @map("client_name") @db.VarChar(200)
  projectName     String?   @map("project_name") @db.VarChar(200)
  contractNumber  String    @map("contract_number") @db.VarChar(30)
  status          String    @default("draft") @db.VarChar(20)
  startDate       DateTime? @map("start_date") @db.Date
  endDate         DateTime? @map("end_date") @db.Date
  amount          BigInt    @default(0)
  taxAmount       BigInt    @default(0) @map("tax_amount")
  totalAmount     BigInt    @default(0) @map("total_amount")
  contractBody    String?   @map("contract_body") @db.LongText
  templateId      Int?      @map("template_id")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

  user            User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  project         Project?  @relation(fields: [projectId], references: [id], onDelete: SetNull)
  client          Client?   @relation(fields: [clientId], references: [id], onDelete: SetNull)
  estimate        Estimate? @relation(fields: [estimateId], references: [id], onDelete: SetNull)
  milestones      ContractMilestone[]
  settlements     Settlement[]

  @@index([userId, status])
  @@map("contracts")
}

model ContractMilestone {
  id            Int     @id @default(autoincrement())
  contractId    Int     @map("contract_id")
  label         String  @db.VarChar(200)
  percentage    Int     @default(0)
  amount        BigInt  @default(0)
  conditionNote String? @map("condition_note") @db.VarChar(500)
  sortOrder     Int     @default(0) @map("sort_order")

  contract      Contract @relation(fields: [contractId], references: [id], onDelete: Cascade)

  @@map("contract_milestones")
}

// ========================
// Tax Invoice
// ========================
model TaxInvoice {
  id                    Int       @id @default(autoincrement())
  userId                Int       @map("user_id")
  projectId             Int?      @map("project_id")
  settlementId          Int?      @map("settlement_id")
  clientName            String?   @map("client_name") @db.VarChar(200)
  projectName           String?   @map("project_name") @db.VarChar(200)
  invoiceNumber         String    @map("invoice_number") @db.VarChar(30)
  status                String    @default("draft") @db.VarChar(20)
  issueDate             DateTime  @map("issue_date") @db.Date
  supplyAmount          BigInt    @default(0) @map("supply_amount")
  taxAmount             BigInt    @default(0) @map("tax_amount")
  totalAmount           BigInt    @default(0) @map("total_amount")
  // Supplier
  supplierRegNo         String?   @map("supplier_reg_no") @db.VarChar(20)
  supplierName          String?   @map("supplier_name") @db.VarChar(200)
  supplierRep           String?   @map("supplier_rep") @db.VarChar(100)
  supplierAddress       String?   @map("supplier_address") @db.VarChar(500)
  supplierBizType       String?   @map("supplier_biz_type") @db.VarChar(100)
  supplierBizItem       String?   @map("supplier_biz_item") @db.VarChar(100)
  supplierContact       String?   @map("supplier_contact") @db.VarChar(100)
  supplierEmail         String?   @map("supplier_email") @db.VarChar(255)
  // Recipient
  recipientRegNo        String?   @map("recipient_reg_no") @db.VarChar(20)
  recipientName         String?   @map("recipient_name") @db.VarChar(200)
  recipientRep          String?   @map("recipient_rep") @db.VarChar(100)
  recipientAddress      String?   @map("recipient_address") @db.VarChar(500)
  recipientBizType      String?   @map("recipient_biz_type") @db.VarChar(100)
  recipientBizItem      String?   @map("recipient_biz_item") @db.VarChar(100)
  recipientContact      String?   @map("recipient_contact") @db.VarChar(100)
  recipientEmail        String?   @map("recipient_email") @db.VarChar(255)
  // Payment
  paymentCash           BigInt    @default(0) @map("payment_cash")
  paymentCheck          BigInt    @default(0) @map("payment_check")
  paymentNote           BigInt    @default(0) @map("payment_note")
  paymentReceivable     BigInt    @default(0) @map("payment_receivable")
  receiptType           String    @default("receipt") @map("receipt_type") @db.VarChar(10)
  remark                String?   @db.Text
  // Correction
  isCorrection          Boolean   @default(false) @map("is_correction")
  originalInvoiceId     Int?      @map("original_invoice_id")
  // NTS
  ntsSubmissionStatus   String    @default("pending") @map("nts_submission_status") @db.VarChar(20)
  ntsSubmissionDate     DateTime? @map("nts_submission_date")
  clientId              Int?      @map("client_id")
  createdAt             DateTime  @default(now()) @map("created_at")
  updatedAt             DateTime  @updatedAt @map("updated_at")

  user                  User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  project               Project?  @relation(fields: [projectId], references: [id], onDelete: SetNull)
  client                Client?   @relation(fields: [clientId], references: [id], onDelete: SetNull)
  items                 TaxInvoiceItem[]

  @@index([userId, status])
  @@map("tax_invoices")
}

model TaxInvoiceItem {
  id            Int     @id @default(autoincrement())
  taxInvoiceId  Int     @map("tax_invoice_id")
  month         String? @db.VarChar(2)
  day           String? @db.VarChar(2)
  itemName      String? @map("item_name") @db.VarChar(300)
  specification String? @db.VarChar(200)
  quantity      Int     @default(1)
  unitPrice     BigInt  @default(0) @map("unit_price")
  supplyAmount  BigInt  @default(0) @map("supply_amount")
  taxAmount     BigInt  @default(0) @map("tax_amount")
  remark        String? @db.VarChar(500)
  sortOrder     Int     @default(0) @map("sort_order")

  taxInvoice    TaxInvoice @relation(fields: [taxInvoiceId], references: [id], onDelete: Cascade)

  @@map("tax_invoice_items")
}

// ========================
// Cash Receipt
// ========================
model CashReceipt {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  receiptNumber   String    @map("receipt_number") @db.VarChar(30)
  status          String    @default("draft") @db.VarChar(20)
  issueType       String    @default("income-deduction") @map("issue_type") @db.VarChar(30)
  identityType    String    @default("card") @map("identity_type") @db.VarChar(20)
  identityNumber  String?   @map("identity_number") @db.VarChar(50)
  consumerName    String?   @map("consumer_name") @db.VarChar(200)
  issueDate       DateTime  @map("issue_date") @db.Date
  supplyAmount    BigInt    @default(0) @map("supply_amount")
  taxAmount       BigInt    @default(0) @map("tax_amount")
  totalAmount     BigInt    @default(0) @map("total_amount")
  remark          String?   @db.Text
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

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

  @@index([userId, status])
  @@map("cash_receipts")
}

model CashReceiptItem {
  id            Int     @id @default(autoincrement())
  cashReceiptId Int     @map("cash_receipt_id")
  itemName      String? @map("item_name") @db.VarChar(300)
  amount        BigInt  @default(0)
  sortOrder     Int     @default(0) @map("sort_order")

  cashReceipt   CashReceipt @relation(fields: [cashReceiptId], references: [id], onDelete: Cascade)

  @@map("cash_receipt_items")
}

// ========================
// Settlement
// ========================
model Settlement {
  id                Int       @id @default(autoincrement())
  userId            Int       @map("user_id")
  projectId         Int?      @map("project_id")
  clientId          Int?      @map("client_id")
  contractId        Int?      @map("contract_id")
  settlementNumber  String    @map("settlement_number") @db.VarChar(30)
  amount            BigInt    @default(0)
  taxAmount         BigInt    @default(0) @map("tax_amount")
  totalAmount       BigInt    @default(0) @map("total_amount")
  settlementDate    DateTime  @map("settlement_date") @db.Date
  taxInvoiceStatus  String    @default("pending") @map("tax_invoice_status") @db.VarChar(20)
  paymentStatus     String    @default("waiting") @map("payment_status") @db.VarChar(20)
  paymentMethod     String?   @map("payment_method") @db.VarChar(50)
  paymentMethodEn   String?   @map("payment_method_en") @db.VarChar(50)
  note              String?   @db.Text
  noteEn            String?   @map("note_en") @db.Text
  createdAt         DateTime  @default(now()) @map("created_at")
  updatedAt         DateTime  @updatedAt @map("updated_at")

  user              User      @relation(fields: [userId], references: [id], onDelete: Cascade)
  project           Project?  @relation(fields: [projectId], references: [id], onDelete: SetNull)
  client            Client?   @relation(fields: [clientId], references: [id], onDelete: SetNull)
  contract          Contract? @relation(fields: [contractId], references: [id], onDelete: SetNull)
  payments          SettlementPayment[]

  @@index([userId, settlementDate])
  @@index([paymentStatus])
  @@map("settlements")
}

model SettlementPayment {
  id            Int      @id @default(autoincrement())
  settlementId  Int      @map("settlement_id")
  paymentDate   DateTime @map("payment_date") @db.Date
  amount        BigInt
  method        String?  @db.VarChar(50)
  methodEn      String?  @map("method_en") @db.VarChar(50)
  createdAt     DateTime @default(now()) @map("created_at")

  settlement    Settlement @relation(fields: [settlementId], references: [id], onDelete: Cascade)

  @@map("settlement_payments")
}

// ========================
// Purchase/Sale Record
// ========================
model PurchaseSaleRecord {
  id               Int       @id @default(autoincrement())
  userId           Int       @map("user_id")
  recordNumber     String    @map("record_number") @db.VarChar(30)
  recordDate       DateTime  @map("record_date") @db.Date
  tradeType        String    @map("trade_type") @db.VarChar(10)
  docType          String    @map("doc_type") @db.VarChar(20)
  partner          String    @db.VarChar(200)
  partnerEn        String?   @map("partner_en") @db.VarChar(200)
  partnerRegNo     String?   @map("partner_reg_no") @db.VarChar(20)
  supplyAmount     BigInt    @default(0) @map("supply_amount")
  taxAmount        BigInt    @default(0) @map("tax_amount")
  total            BigInt    @default(0)
  memo             String?   @db.Text
  memoEn           String?   @map("memo_en") @db.Text
  projectId        Int?      @map("project_id")
  projectName      String?   @map("project_name") @db.VarChar(200)
  milestoneType    String?   @map("milestone_type") @db.VarChar(20)
  dueDate          DateTime? @map("due_date") @db.Date
  source           String?   @db.VarChar(20)
  linkedSettlementId Int?    @map("linked_settlement_id")
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @updatedAt @map("updated_at")

  user             User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  project          Project? @relation(fields: [projectId], references: [id], onDelete: SetNull)

  @@index([userId, tradeType, recordDate])
  @@map("purchase_sale_records")
}

// ========================
// Expense
// ========================
model ExpenseCategory {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  nameKo    String   @map("name_ko") @db.VarChar(100)
  nameEn    String   @map("name_en") @db.VarChar(100)
  slug      String   @db.VarChar(50)
  isSystem  Boolean  @default(false) @map("is_system")
  createdAt DateTime @default(now()) @map("created_at")

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

  @@index([userId])
  @@map("expense_categories")
}

model Expense {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  categoryId      Int?      @map("category_id")
  expenseDate     DateTime  @map("expense_date") @db.Date
  item            String    @db.VarChar(300)
  itemEn          String?   @map("item_en") @db.VarChar(300)
  amount          BigInt
  paymentMethod   String?   @map("payment_method") @db.VarChar(100)
  paymentMethodEn String?   @map("payment_method_en") @db.VarChar(100)
  proof           String?   @db.VarChar(100)
  proofEn         String?   @map("proof_en") @db.VarChar(100)
  autoImported    Boolean   @default(false) @map("auto_imported")
  status          String    @default("pending") @db.VarChar(20)
  linkedAccountId Int?      @map("linked_account_id")
  receiptUrl      String?   @map("receipt_url") @db.VarChar(500)
  note            String?   @db.Text
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

  user            User           @relation(fields: [userId], references: [id], onDelete: Cascade)
  category        ExpenseCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)

  @@index([userId, expenseDate])
  @@map("expenses")
}

model FixedExpense {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  categoryId      Int?      @map("category_id")
  name            String    @db.VarChar(200)
  nameEn          String?   @map("name_en") @db.VarChar(200)
  amount          BigInt
  billingCycle    String    @default("monthly") @map("billing_cycle") @db.VarChar(20)
  nextBillingDate DateTime? @map("next_billing_date") @db.Date
  isActive        Boolean   @default(true) @map("is_active")
  autoImport      Boolean   @default(false) @map("auto_import")
  createdAt       DateTime  @default(now()) @map("created_at")
  updatedAt       DateTime  @updatedAt @map("updated_at")

  user            User           @relation(fields: [userId], references: [id], onDelete: Cascade)
  category        ExpenseCategory? @relation(fields: [categoryId], references: [id], onDelete: SetNull)

  @@map("fixed_expenses")
}

// ========================
// Template
// ========================
model Template {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  type      String   @db.VarChar(20)
  name      String   @db.VarChar(200)
  nameEn    String?  @map("name_en") @db.VarChar(200)
  content   Json?
  isDefault Boolean  @default(false) @map("is_default")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

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

  @@index([userId, type])
  @@map("templates")
}

// ========================
// AI Chat
// ========================
model AiConversation {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  title     String?  @db.VarChar(300)
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

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

  @@map("ai_conversations")
}

model AiMessage {
  id             Int      @id @default(autoincrement())
  conversationId Int      @map("conversation_id")
  role           String   @db.VarChar(10)
  content        String   @db.Text
  richContent    Json?    @map("rich_content")
  stage          Int?
  createdAt      DateTime @default(now()) @map("created_at")

  conversation   AiConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)

  @@index([conversationId])
  @@map("ai_messages")
}

// ========================
// Subscription & Billing
// ========================
model Plan {
  id           Int      @id @default(autoincrement())
  planId       String   @unique @map("plan_id") @db.VarChar(20)
  name         String   @db.VarChar(100)
  nameKo       String   @map("name_ko") @db.VarChar(100)
  price        Int      @default(0)
  creditBonus  Int      @default(0) @map("credit_bonus")
  totalCredits Int      @default(0) @map("total_credits")
  features     Json?
  featuresEn   Json?    @map("features_en")
  isActive     Boolean  @default(true) @map("is_active")
  createdAt    DateTime @default(now()) @map("created_at")

  subscriptions        Subscription[]
  pendingSubscriptions Subscription[] @relation("PendingPlan")

  @@map("plans")
}

model Subscription {
  id                  Int       @id @default(autoincrement())
  userId              Int       @unique @map("user_id")
  planId              Int       @map("plan_id")
  status              String    @default("trial") @db.VarChar(20)
  currentPeriodStart  DateTime? @map("current_period_start") @db.Date
  currentPeriodEnd    DateTime? @map("current_period_end") @db.Date
  cancelAtPeriodEnd   Boolean   @default(false) @map("cancel_at_period_end")
  tossCustomerKey     String?   @map("toss_customer_key") @db.VarChar(100)
  tossBillingKey      String?   @map("toss_billing_key") @db.VarChar(100)
  billingAnchorDay    Int       @default(1) @map("billing_anchor_day")
  nextBillingDate     DateTime? @map("next_billing_date") @db.Date
  pendingPlanId       Int?      @map("pending_plan_id")
  lastBillingStatus   String    @default("none") @map("last_billing_status") @db.VarChar(20)
  createdAt           DateTime  @default(now()) @map("created_at")
  updatedAt           DateTime  @updatedAt @map("updated_at")

  user        User  @relation(fields: [userId], references: [id], onDelete: Cascade)
  plan        Plan  @relation(fields: [planId], references: [id])
  pendingPlan Plan? @relation("PendingPlan", fields: [pendingPlanId], references: [id])

  @@map("subscriptions")
}

model BillingHistory {
  id              Int       @id @default(autoincrement())
  userId          Int       @map("user_id")
  type            String    @db.VarChar(20)
  referenceId     Int?      @map("reference_id")
  amount          Int
  status          String    @db.VarChar(20)
  tossOrderId     String?   @map("toss_order_id") @db.VarChar(100)
  tossPaymentKey  String?   @map("toss_payment_key") @db.VarChar(200)
  description     String?   @db.VarChar(500)
  periodStart     DateTime? @map("period_start") @db.Date
  periodEnd       DateTime? @map("period_end") @db.Date
  createdAt       DateTime  @default(now()) @map("created_at")

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

  @@index([userId, createdAt])
  @@map("billing_history")
}

model Addon {
  id            Int      @id @default(autoincrement())
  addonId       String   @unique @map("addon_id") @db.VarChar(30)
  name          String   @db.VarChar(100)
  nameKo        String   @map("name_ko") @db.VarChar(100)
  price         Int      @default(0)
  unit          String?  @db.VarChar(50)
  unitKo        String?  @map("unit_ko") @db.VarChar(50)
  description   String?  @db.Text
  descriptionKo String?  @map("description_ko") @db.Text
  perUnit       Boolean  @default(false) @map("per_unit")
  isActive      Boolean  @default(true) @map("is_active")
  createdAt     DateTime @default(now()) @map("created_at")

  subscriptions AddonSubscription[]

  @@map("addons")
}

model AddonSubscription {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  addonId   Int      @map("addon_id")
  quantity  Int      @default(1)
  isActive  Boolean  @default(true) @map("is_active")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

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

  @@unique([userId, addonId])
  @@map("addon_subscriptions")
}

// ========================
// Credit / Wallet
// ========================
model CreditSettings {
  id                   Int     @id @default(autoincrement())
  userId               Int     @unique @map("user_id")
  balance              Int     @default(0)
  autoCharge           Boolean @default(false) @map("auto_charge")
  autoChargeThreshold  Int     @default(5000) @map("auto_charge_threshold")
  autoChargeAmount     Int     @default(30000) @map("auto_charge_amount")
  lowBalanceAlert      Boolean @default(true) @map("low_balance_alert")

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

  @@map("credit_settings")
}

model CreditTransaction {
  id            Int      @id @default(autoincrement())
  userId        Int      @map("user_id")
  type          String   @db.VarChar(10)
  description   String   @db.VarChar(500)
  amount        Int
  balanceAfter  Int      @map("balance_after")
  referenceType String?  @map("reference_type") @db.VarChar(50)
  referenceId   Int?     @map("reference_id")
  createdAt     DateTime @default(now()) @map("created_at")

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

  @@index([userId, createdAt])
  @@map("credit_transactions")
}

// ========================
// Payment Method
// ========================
model PaymentMethod {
  id             Int      @id @default(autoincrement())
  userId         Int      @map("user_id")
  brand          String   @db.VarChar(20)
  last4          String   @db.VarChar(4)
  holderName     String?  @map("holder_name") @db.VarChar(100)
  expiry         String?  @db.VarChar(10)
  isDefault      Boolean  @default(false) @map("is_default")
  tossBillingKey String?  @map("toss_billing_key") @db.VarChar(200)
  createdAt      DateTime @default(now()) @map("created_at")

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

  @@index([userId])
  @@map("payment_methods")
}

// ========================
// Integration (Linked Accounts)
// ========================
model LinkedAccount {
  id               Int       @id @default(autoincrement())
  userId           Int       @map("user_id")
  type             String    @db.VarChar(10)
  provider         String    @db.VarChar(50)
  providerEn       String?   @map("provider_en") @db.VarChar(50)
  accountNumber    String?   @map("account_number") @db.VarChar(50)
  alias            String?   @db.VarChar(100)
  aliasEn          String?   @map("alias_en") @db.VarChar(100)
  status           String    @default("connected") @db.VarChar(20)
  autoImport       Boolean   @default(true) @map("auto_import")
  lastSyncAt       DateTime? @map("last_sync_at")
  transactionCount Int       @default(0) @map("transaction_count")
  monthlyImported  Int       @default(0) @map("monthly_imported")
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @updatedAt @map("updated_at")

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

  @@index([userId, type])
  @@map("linked_accounts")
}

// ========================
// Notification
// ========================
model Notification {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  type      String   @db.VarChar(50)
  title     String   @db.VarChar(300)
  message   String?  @db.Text
  link      String?  @db.VarChar(500)
  isRead    Boolean  @default(false) @map("is_read")
  createdAt DateTime @default(now()) @map("created_at")

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

  @@index([userId, isRead])
  @@map("notifications")
}
