// =============================================
// PRISMA SCHEMA - HQLAND MANAGEMENT SYSTEM
// Phiên bản: 2.4 (Cập nhật từ Database thực tế)
// Ngày: 18/04/2026
// Ghi chú: Đồng bộ hóa 100% với Migrations hiện tại.
// =============================================

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

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

// =============================================
// 1. PROJECT (Dự án)
// =============================================
model Project {
  id          String   @id @default(uuid())
  code        String   @unique   // ví dụ: STH03
  name        String
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

  products    Product[]
  templates   PaymentTemplate[]
}

// =============================================
// 2. PRODUCT (Sản phẩm)
// =============================================
model Product {
  id                        String       @id @default(uuid())
  projectId                 String       @map("project_id")

  productType               String       @map("product_type") // LAND, APARTMENT...

  code                      String       @unique
  area                      Decimal      @db.Decimal(12, 2)
  pricePerUnit              Decimal      @db.Decimal(15, 2) @map("price_per_unit")
  totalPrice                Decimal      @db.Decimal(15, 2) @map("total_price")

  // Giá trị tài chính bổ sung
  qsddValue                 Decimal      @default(0) @db.Decimal(15, 2) @map("qsdd_value")
  foundationTempValue       Decimal      @default(0) @db.Decimal(15, 2) @map("foundation_temp_value")
  contractTempValue         Decimal      @default(0) @db.Decimal(15, 2) @map("contract_temp_value")

  // Thông số kỹ thuật
  adjacentRoad              String?      @map("adjacent_road")
  frontageCount             Int?         @map("frontage_count")
  maxFloors                 Int?         @map("max_floors")
  buildingDensity           Decimal?     @db.Decimal(5, 2) @map("building_density")
  constructionStatus        String?      @map("construction_status")

  // Hạ tầng & Dữ liệu động
  infrastructureRawText     String?      @map("infrastructure_raw_text")
  infrastructureStatus      Json?        @map("infrastructure_status")
  customData                Json?        @map("custom_data")

  // Trạng thái
  status                    String       @default("Đang mở bán")
  redBookStatus             String       @default("Chưa có dữ liệu") @map("red_book_status")

  createdAt                 DateTime     @default(now()) @map("created_at")
  updatedAt                 DateTime     @updatedAt @map("updated_at")

  project                   Project      @relation(fields: [projectId], references: [id])
  contracts                 Contract[]
  settlements               Settlement[]
}

// =============================================
// 3. CONTRACT & CUSTOMER
// =============================================
model Contract {
  id                String   @id @default(uuid())
  productId         String   @map("product_id")
  transferOrder     Int      @default(0) @map("transfer_order")
  contractType      String   @default("HĐMB") @map("contract_type")
  contractNumber    String   @unique @map("contract_number")
  signingDate       DateTime? @map("signing_date")
  status            String   @default("Đang hiệu lực")
  
  totalValue        Decimal  @db.Decimal(15, 2) @map("total_value")
  paidAmount        Decimal  @default(0) @db.Decimal(15, 2) @map("paid_amount")
  remainingAmount   Decimal  @default(0) @db.Decimal(15, 2) @map("remaining_amount")
  excessAmount      Decimal  @default(0) @db.Decimal(15, 2) @map("excess_amount") // Tiền dư

  metadata          Json?
  createdAt         DateTime @default(now()) @map("created_at")
  updatedAt         DateTime @updatedAt @map("updated_at")

  product           Product  @relation(fields: [productId], references: [id])
  customers         ContractCustomer[]
  appendices        Appendix[]
  payments          Payment[]
  schedule          PaymentSchedule?
  fines             PaymentFine[]
}

model Customer {
  id          String   @id @default(uuid())
  cmndCccd    String   @unique @map("cmnd_cccd")
  fullName    String   @map("full_name")
  phone       String?
  email       String?
  address     Json?
  dob         DateTime?
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

  contracts   ContractCustomer[]
}

model ContractCustomer {
  id            BigInt   @id @default(autoincrement())
  contractId    String   @map("contract_id")
  customerId    String   @map("customer_id")
  role          String   @default("CHỦ SH 1")
  transferOrder Int      @default(0) @map("transfer_order")
  createdAt     DateTime @default(now()) @map("created_at")
  updatedAt     DateTime @updatedAt @map("updated_at")

  contract      Contract @relation(fields: [contractId], references: [id])
  customer      Customer @relation(fields: [customerId], references: [id])
}

// =============================================
// 4. FINANCE MODULE
// =============================================
model PaymentTemplate {
  id          String   @id @default(uuid())
  projectId   String   @map("project_id")
  name        String
  isDefault   Boolean  @default(false) @map("is_default")
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

  project     Project  @relation(fields: [projectId], references: [id])
  items       PaymentScheduleItem[]
  schedules   PaymentSchedule[]
}

model PaymentSchedule {
  id          String   @id @default(uuid())
  contractId  String   @unique @map("contract_id")
  templateId  String   @map("template_id")
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

  contract    Contract @relation(fields: [contractId], references: [id])
  template    PaymentTemplate @relation(fields: [templateId], references: [id])
  items       PaymentScheduleItem[]
}

model PaymentScheduleItem {
  id                String      @id @default(uuid())
  templateId        String?     @map("template_id")
  scheduleId        String?     @map("schedule_id")

  installmentNo     Int         @map("installment_no")
  amount            Decimal?    @db.Decimal(15, 2)
  percentage        Decimal?    @db.Decimal(5, 2)

  // Logic ngày đến hạn
  daysAfterSigning  Int?        @map("days_after_signing")
  daysAfterPrevious Int?        @map("days_after_previous")
  dueDate           DateTime?   @map("due_date")

  type              String      // QSDD, MONG, THAN...
  createdAt         DateTime @default(now()) @map("created_at")
  updatedAt         DateTime @updatedAt @map("updated_at")

  template          PaymentTemplate? @relation(fields: [templateId], references: [id])
  schedule          PaymentSchedule? @relation(fields: [scheduleId], references: [id])
  payments          Payment[]
}

model Payment {
  id              String   @id @default(uuid())
  contractId      String   @map("contract_id")
  scheduleItemId  String?  @map("schedule_item_id")

  amount          Decimal  @db.Decimal(15, 2)
  paidDate        DateTime @map("paid_date")
  receiptNumber   String?  @map("receipt_number")
  method          String   @default("Chuyển khoản")
  metadata        Json?
  createdAt       DateTime @default(now()) @map("created_at")
  updatedAt       DateTime @updatedAt @map("updated_at")

  contract        Contract @relation(fields: [contractId], references: [id])
  scheduleItem    PaymentScheduleItem? @relation(fields: [scheduleItemId], references: [id])
}

model PaymentFine {
  id          String   @id @default(uuid())
  contractId  String   @map("contract_id")
  amount      Decimal  @db.Decimal(15, 2)
  reason      String
  dueDate     DateTime @map("due_date")
  paidDate    DateTime? @map("paid_date")
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @updatedAt @map("updated_at")

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

// =============================================
// 5. APPENDIX & SETTLEMENT
// =============================================
model Appendix {
  id               String   @id @default(uuid())
  contractId       String   @map("contract_id")
  productId        String   @map("product_id")
  type             String
  applyFromOrder   Int      @map("apply_from_order")
  signingDate      DateTime @map("signing_date")
  customData       Json?    @map("custom_data")
  createdAt        DateTime @default(now()) @map("created_at")
  updatedAt        DateTime @updatedAt @map("updated_at")

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

model Settlement {
  id            String   @id @default(uuid())
  productId     String   @map("product_id")
  type          String   // MONG, THAN, CP THI CONG
  tempValue     Decimal  @db.Decimal(15, 2) @map("temp_value")
  finalValue    Decimal  @db.Decimal(15, 2) @map("final_value")
  difference    Decimal  @db.Decimal(15, 2)
  redBookStatus String   @map("red_book_status")
  issueDate     DateTime? @map("issue_date")
  createdAt     DateTime @default(now()) @map("created_at")
  updatedAt     DateTime @updatedAt @map("updated_at")

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