package domain

import (
	"time"

	"gorm.io/gorm"
)

// BaseModel for all entities
type BaseModel struct {
	ID        uint           `gorm:"primaryKey;autoIncrement;comment:'Internal PK'" json:"id"`
	CreatedAt time.Time      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt time.Time      `gorm:"autoUpdateTime" json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

// Users
type User struct {
	BaseModel
	FullName     string `gorm:"column:full_name;size:150;not null" json:"full_name" validate:"required"`
	Username     string `gorm:"size:100;not null;unique;index" json:"username" validate:"required,min=4"`
	PasswordHash string `gorm:"size:255;not null" json:"-"`
	Role         string `gorm:"size:20;not null;default:'staff'" json:"role" validate:"required,oneof=admin manager staff user superadmin"`
	IsActive     bool   `gorm:"default:true" json:"is_active"`
	BranchID     uint   `gorm:"column:branch_id;default:1" json:"branch_id"`
}

type Role struct {
	BaseModel
	Name        string `gorm:"size:50;not null;unique" json:"name" validate:"required"`
	Description string `gorm:"size:150" json:"description"`
}

// Service Requisition (Header)
type ServiceRequisition struct {
	BaseModel
	Ref               string     `gorm:"size:50;unique;not null;index:idx_ref" json:"ref" validate:"required"`
	Date              time.Time  `gorm:"type:date;not null;index:idx_date" json:"date"`
	ChargeTo          string     `gorm:"size:150" json:"charge_to"`
	To                string     `gorm:"column:to;size:150" json:"to"`
	From              string     `gorm:"column:from;size:150" json:"from"`
	CC                string     `gorm:"size:150" json:"cc"`
	ProductMgr        string     `gorm:"size:150" json:"product_mgr"`
	Customer          string     `gorm:"size:150" json:"customer" validate:"required"`
	EquipmentLocation string     `gorm:"size:255" json:"equipment_location"`
	SalesAgreementNo  string     `gorm:"column:sales_agreement_no;size:100" json:"sales_agreement_no"`
	Description       string     `gorm:"type:text" json:"description"`
	RequestedBy       string     `gorm:"size:150" json:"requested_by"`
	ReceivedBy        string     `gorm:"size:150" json:"received_by"`
	ApprovedBy        string     `gorm:"size:150" json:"approved_by"` // Manager
	ApprovedAt        *time.Time `json:"approved_at,omitempty"`
	DeptMgr           string     `gorm:"size:150" json:"dept_mgr"` // Dept Mgr / Marketing Div Mgr
	Status            string     `gorm:"size:20;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber    int        `gorm:"default:0" json:"revision_number"`
	CreatedBy         *uint      `json:"created_by"`
	BranchID          uint       `gorm:"index" json:"branch_id"`

	Checklist  *ServiceRequisitionChecklist  `gorm:"foreignKey:ServiceRequisitionID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"checklist,omitempty"`
	Equipments []ServiceRequisitionEquipment `gorm:"foreignKey:ServiceRequisitionID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"equipments,omitempty"`
}

// Service Requisition Checklist
type ServiceRequisitionChecklist struct {
	BaseModel
	ServiceRequisitionID uint `gorm:"uniqueIndex:unique_sr;not null" json:"service_requisition_id"`
	PreDeliveryCheck     bool `gorm:"default:false" json:"pre_delivery_check"`
	DeliveryCheck        bool `gorm:"default:false" json:"delivery_check"`
	PeriodicMaintenance  bool `gorm:"default:false" json:"periodic_maintenance"`
	Repair               bool `gorm:"default:false" json:"repair"`
	Assemble             bool `gorm:"default:false" json:"assemble"`
	Recondition          bool `gorm:"default:false" json:"recondition"`
	Training             bool `gorm:"default:false" json:"training"`
	Other                bool `gorm:"default:false" json:"other"`
	// Scope of Supply (*)
	Unit            bool `gorm:"default:false" json:"unit"`
	PanelCabel      bool `gorm:"default:false" json:"panel_cabel"`
	FuelTank        bool `gorm:"default:false" json:"fuel_tank"`
	ExhaustSystem   bool `gorm:"default:false" json:"exhaust_system"`
	FrontAttachment bool `gorm:"default:false" json:"front_attachment"`
	RearAttachment  bool `gorm:"default:false" json:"rear_attachment"`
	Manuals         bool `gorm:"default:false" json:"manuals"`
	Others          bool `gorm:"default:false" json:"others"`
}

// Service Requisition Equipment
type ServiceRequisitionEquipment struct {
	BaseModel
	ServiceRequisitionID uint   `gorm:"not null;index:idx_sr_id" json:"service_requisition_id"`
	No                   int    `gorm:"not null" json:"no"`
	Brand                string `gorm:"size:100" json:"brand"`
	Model                string `gorm:"size:100" json:"model"`
	SerialNumber         string `gorm:"size:100" json:"serial_number"`
	Qty                  int    `gorm:"default:1" json:"qty"`
	MHPNo                string `gorm:"column:mhp_no;size:100" json:"mhp_no"`
	TableBlock           int    `gorm:"default:1" json:"table_block"`
}

// ---------------------------------------------------------
// NEW: MEMO SERVICE PARTS
// ---------------------------------------------------------

type MemoServiceParts struct {
	BaseModel
	Ref               string     `gorm:"size:50;unique;not null;index:idx_parts_ref" json:"ref" validate:"required"`
	Date              time.Time  `gorm:"type:date;not null;index:idx_parts_date" json:"date"`
	ChargeTo          string     `gorm:"size:150" json:"charge_to"`
	To                string     `gorm:"column:to;size:150" json:"to"`
	From              string     `gorm:"column:from;size:150" json:"from"`
	CC                string     `gorm:"size:150" json:"cc"`
	ProductMgr        string     `gorm:"size:150" json:"product_mgr"`
	Customer          string     `gorm:"size:150" json:"customer" validate:"required"`
	EquipmentLocation string     `gorm:"size:255" json:"equipment_location"`
	SalesAgreementNo  string     `gorm:"column:sales_agreement_no;size:100" json:"sales_agreement_no"`
	Description       string     `gorm:"type:text" json:"description"`
	RequestedBy       string     `gorm:"size:150" json:"requested_by"`
	ReceivedBy        string     `gorm:"size:150" json:"received_by"`
	ApprovedBy        string     `gorm:"size:150" json:"approved_by"` // Manager
	ApprovedAt        *time.Time `json:"approved_at,omitempty"`
	DeptMgr           string     `gorm:"size:150" json:"dept_mgr"` // Dept Mgr / Marketing Div Mgr
	Status            string     `gorm:"size:20;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber    int        `gorm:"default:0" json:"revision_number"`
	CreatedBy         *uint      `json:"created_by"`
	BranchID          uint       `gorm:"index" json:"branch_id"`
	EngineUnit        string     `gorm:"size:150" json:"engine_unit"`
	ESNNumber         string     `gorm:"size:100" json:"esn_number"`
	SpvName           string     `gorm:"size:150" json:"spv_name"`
	SpvPosition       string     `gorm:"size:100" json:"spv_position"`
	Subject           string     `gorm:"size:255" json:"subject"`

	Checklist  *MemoServicePartsChecklist  `gorm:"foreignKey:MemoServicePartsID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"checklist,omitempty"`
	Equipments []MemoServicePartsEquipment `gorm:"foreignKey:MemoServicePartsID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"equipments,omitempty"`
}

type MemoServicePartsChecklist struct {
	BaseModel
	MemoServicePartsID   uint `gorm:"uniqueIndex:idx_parts_checklist_sr_id;not null" json:"memo_service_parts_id"`
	PreDeliveryCheck     bool `gorm:"default:false" json:"pre_delivery_check"`
	DeliveryCheck        bool `gorm:"default:false" json:"delivery_check"`
	PeriodicMaintenance  bool `gorm:"default:false" json:"periodic_maintenance"`
	Repair               bool `gorm:"default:false" json:"repair"`
	Assemble             bool `gorm:"default:false" json:"assemble"`
	Recondition          bool `gorm:"default:false" json:"recondition"`
	Training             bool `gorm:"default:false" json:"training"`
	Other                bool `gorm:"default:false" json:"other"`
	Unit            bool `gorm:"default:false" json:"unit"`
	PanelCabel      bool `gorm:"default:false" json:"panel_cabel"`
	FuelTank        bool `gorm:"default:false" json:"fuel_tank"`
	ExhaustSystem   bool `gorm:"default:false" json:"exhaust_system"`
	FrontAttachment bool `gorm:"default:false" json:"front_attachment"`
	RearAttachment  bool `gorm:"default:false" json:"rear_attachment"`
	Manuals         bool `gorm:"default:false" json:"manuals"`
	Others          bool `gorm:"default:false" json:"others"`
}

type MemoServicePartsEquipment struct {
	BaseModel
	MemoServicePartsID   uint   `gorm:"not null;index:idx_parts_id" json:"memo_service_parts_id"`
	No                   int    `gorm:"not null" json:"no"`
	Brand                string `gorm:"size:100" json:"brand"`
	Model                string `gorm:"size:100" json:"model"`
	SerialNumber         string `gorm:"size:100" json:"serial_number"`
	Qty                  int    `gorm:"default:1" json:"qty"`
	MHPNo                string `gorm:"column:mhp_no;size:100" json:"mhp_no"`
	TableBlock           int    `gorm:"default:1" json:"table_block"`
}

// ---------------------------------------------------------
// NEW: MEMO SERVICE KALIBRASI
// ---------------------------------------------------------

type MemoServiceKalibrasi struct {
	BaseModel
	Ref               string     `gorm:"size:50;unique;not null;index:idx_kalibrasi_ref" json:"ref" validate:"required"`
	Date              time.Time  `gorm:"type:date;not null;index:idx_kalibrasi_date" json:"date"`
	ChargeTo          string     `gorm:"size:150" json:"charge_to"`
	To                string     `gorm:"column:to;size:150" json:"to"`
	From              string     `gorm:"column:from;size:150" json:"from"`
	CC                string     `gorm:"size:150" json:"cc"`
	ProductMgr        string     `gorm:"size:150" json:"product_mgr"`
	Customer          string     `gorm:"size:150" json:"customer" validate:"required"`
	EquipmentLocation string     `gorm:"size:255" json:"equipment_location"`
	SalesAgreementNo  string     `gorm:"column:sales_agreement_no;size:100" json:"sales_agreement_no"`
	Description       string     `gorm:"type:text" json:"description"`
	RequestedBy       string     `gorm:"size:150" json:"requested_by"`
	ReceivedBy        string     `gorm:"size:150" json:"received_by"`
	ApprovedBy        string     `gorm:"size:150" json:"approved_by"` // Manager
	ApprovedAt        *time.Time `json:"approved_at,omitempty"`
	DeptMgr           string     `gorm:"size:150" json:"dept_mgr"` // Dept Mgr / Marketing Div Mgr
	Status            string     `gorm:"size:20;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber    int        `gorm:"default:0" json:"revision_number"`
	CreatedBy         *uint      `json:"created_by"`
	BranchID          uint       `gorm:"index" json:"branch_id"`
	EngineUnit        string     `gorm:"size:150" json:"engine_unit"`
	ESNNumber         string     `gorm:"size:100" json:"esn_number"`
	ComponentName     string     `gorm:"size:150" json:"component_name"`
	SpvName           string     `gorm:"size:150" json:"spv_name"`
	SpvPosition       string     `gorm:"size:100" json:"spv_position"`
	Subject           string     `gorm:"size:255" json:"subject"`

	Checklist  *MemoServiceKalibrasiChecklist  `gorm:"foreignKey:MemoServiceKalibrasiID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"checklist,omitempty"`
	Equipments []MemoServiceKalibrasiEquipment `gorm:"foreignKey:MemoServiceKalibrasiID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"equipments,omitempty"`
}

type MemoServiceKalibrasiChecklist struct {
	BaseModel
	MemoServiceKalibrasiID uint `gorm:"uniqueIndex:idx_kalibrasi_checklist_sr_id;not null" json:"memo_service_kalibrasi_id"`
	PreDeliveryCheck     bool `gorm:"default:false" json:"pre_delivery_check"`
	DeliveryCheck        bool `gorm:"default:false" json:"delivery_check"`
	PeriodicMaintenance  bool `gorm:"default:false" json:"periodic_maintenance"`
	Repair               bool `gorm:"default:false" json:"repair"`
	Assemble             bool `gorm:"default:false" json:"assemble"`
	Recondition          bool `gorm:"default:false" json:"recondition"`
	Training             bool `gorm:"default:false" json:"training"`
	Other                bool `gorm:"default:false" json:"other"`
	Unit            bool `gorm:"default:false" json:"unit"`
	PanelCabel      bool `gorm:"default:false" json:"panel_cabel"`
	FuelTank        bool `gorm:"default:false" json:"fuel_tank"`
	ExhaustSystem   bool `gorm:"default:false" json:"exhaust_system"`
	FrontAttachment bool `gorm:"default:false" json:"front_attachment"`
	RearAttachment  bool `gorm:"default:false" json:"rear_attachment"`
	Manuals         bool `gorm:"default:false" json:"manuals"`
	Others          bool `gorm:"default:false" json:"others"`
}

type MemoServiceKalibrasiEquipment struct {
	BaseModel
	MemoServiceKalibrasiID uint   `gorm:"not null;index:idx_kalibrasi_id" json:"memo_service_kalibrasi_id"`
	No                   int    `gorm:"not null" json:"no"`
	Brand                string `gorm:"size:100" json:"brand"`
	Model                string `gorm:"size:100" json:"model"`
	SerialNumber         string `gorm:"size:100" json:"serial_number"`
	Qty                  int    `gorm:"default:1" json:"qty"`
	MHPNo                string `gorm:"column:mhp_no;size:100" json:"mhp_no"`
	TableBlock           int    `gorm:"default:1" json:"table_block"`
}

// Inter-Office Memorandum (IOM)
type Memorandum struct {
	BaseModel
	Ref            string    `gorm:"size:50;unique;not null;index:idx_memo_ref" json:"ref" validate:"required"`
	Date           time.Time `gorm:"type:date;not null" json:"date"`
	ToDepartment   string    `gorm:"size:150" json:"to_department"`
	FromDepartment string    `gorm:"size:150" json:"from_department"`
	Subject        string    `gorm:"size:255" json:"subject" validate:"required"`
	Body           string    `gorm:"type:text" json:"body"`
	SignedBy       string    `gorm:"size:150" json:"signed_by"`
	Status         string    `gorm:"size:20;not null;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber int       `gorm:"default:0" json:"revision_number"`
	CreatedBy      *uint     `json:"created_by"`
	BranchID       uint      `gorm:"index" json:"branch_id"`
}

// Credit Limit Table
type CreditLimit struct {
	BaseModel
	Ref            string    `gorm:"size:80;unique" json:"ref" validate:"required"`
	Date           time.Time `gorm:"type:date" json:"date"`
	Customer       string    `gorm:"size:200" json:"customer" validate:"required"`
	CustomerCode   string    `gorm:"size:50" json:"customer_code"`
	Subject        string    `gorm:"size:255" json:"subject"`
	RequestedLimit float64   `gorm:"type:decimal(18,2)" json:"requested_limit"`
	BusinessLine   string    `gorm:"size:100" json:"business_line"`
	CompanyGroup   string    `gorm:"size:200" json:"company_group"`

	// Units owned - stored as JSON text
	UnitsFromAltrak string `gorm:"type:text" json:"units_from_altrak"`
	UnitsFromOther  string `gorm:"type:text" json:"units_from_other"`

	// Business potential per month
	Spareparts   float64 `gorm:"type:decimal(18,2);default:0" json:"spareparts"`
	FilterAmount float64 `gorm:"type:decimal(18,2);default:0" json:"filter_amount"`
	Valvoline    float64 `gorm:"type:decimal(18,2);default:0" json:"valvoline"`
	Others       float64 `gorm:"type:decimal(18,2);default:0" json:"others"`
	Total        float64 `gorm:"type:decimal(18,2);default:0" json:"total"`

	// Aging A/R
	AgingNotDue   float64 `gorm:"type:decimal(18,2);default:0" json:"aging_not_due"`
	Aging1Month   float64 `gorm:"type:decimal(18,2);default:0" json:"aging_1_month"`
	Aging2Months  float64 `gorm:"type:decimal(18,2);default:0" json:"aging_2_months"`
	Aging3Months  float64 `gorm:"type:decimal(18,2);default:0" json:"aging_3_months"`
	AgingOver3    float64 `gorm:"type:decimal(18,2);default:0" json:"aging_over_3"`
	AgingTotal    float64 `gorm:"type:decimal(18,2);default:0" json:"aging_total"`
	AgingAsOfDate string  `gorm:"size:50" json:"aging_as_of_date"`

	// Signature
	Cc          string `gorm:"size:255" json:"cc"`
	SignedBy    string `gorm:"size:150" json:"signed_by"`
	SignedTitle string `gorm:"size:100" json:"signed_title"`

	Status         string `gorm:"size:20;not null;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber int    `gorm:"default:0" json:"revision_number"`
	CreatedBy      *uint  `json:"created_by"`
	BranchID       uint   `gorm:"index" json:"branch_id"`
}

// Serial Sequence Node
type SerialSequence struct {
	BaseModel
	DocType       string `gorm:"column:doc_type;size:50;not null;uniqueIndex:idx_doc_seq" json:"doc_type"`
	Year          int    `gorm:"not null;uniqueIndex:idx_doc_seq" json:"year"`
	Month         int    `gorm:"not null;uniqueIndex:idx_doc_seq" json:"month"`
	CurrentNumber int    `gorm:"column:current_number;default:0" json:"current_number"`
}

type SystemSetting struct {
	BaseModel
	Key   string `gorm:"size:100;unique;not null;index" json:"key"`
	Value string `gorm:"type:text" json:"value"`
}

// Operational Record (PSO/PO Lifecycle Node)
type OperationalRecord struct {
	BaseModel
	PsoNo        string     `gorm:"column:pso_no;size:191;not null;unique" json:"pso_no" validate:"required"`
	PsoDate      *time.Time `gorm:"column:pso_date" json:"pso_date"`
	PoNo         string     `gorm:"column:po_no;type:longtext" json:"po_no"`
	CustomerName string     `gorm:"column:customer_name;type:longtext" json:"customer_name" validate:"required"`
	AmountIDR    int64      `gorm:"column:amount_idr" json:"amount_idr"` // stored in Cents
	Amount       int64      `gorm:"column:amount" json:"amount"`         // stored in Cents
	RecordStatus string     `gorm:"column:record_status;size:20;default:'DRAFT'" json:"record_status" validate:"required"`
	IsVerified   bool       `gorm:"column:is_verified;default:0" json:"is_verified"`
	VerifiedAt   *time.Time `gorm:"column:verified_at" json:"verified_at"`
	VerifiedBy   *uint      `gorm:"column:verified_by" json:"verified_by"`
	Remark       string     `gorm:"column:remark;type:longtext" json:"remark"`
	TOP          int64      `gorm:"column:top" json:"top"`
	Days         int64      `gorm:"column:days" json:"days"`
	Discount     float64    `gorm:"column:discount" json:"discount"`
	Currency     string     `gorm:"column:currency;size:191;default:'IDR'" json:"currency"`
	BranchID     uint       `gorm:"index" json:"branch_id"`
	// Export tracking: when set, this record has been exported from Daily Reports
	ExportedAt   *time.Time `gorm:"column:exported_at;index" json:"exported_at"`
	ExportedBy   *uint      `gorm:"column:exported_by" json:"exported_by"`
}

type RefreshToken struct {
	BaseModel
	UserID     uint      `gorm:"not null;index" json:"user_id"`
	TokenHash  string    `gorm:"size:255;not null" json:"-"`
	ExpiresAt  time.Time `json:"expires_at"`
	Persistent bool      `gorm:"default:false" json:"persistent"`
	Revoked    bool      `gorm:"default:false" json:"revoked"`
}

type LoginAttempt struct {
	BaseModel
	Key          string    `gorm:"size:255;not null;uniqueIndex" json:"key"`
	FailureCount int       `gorm:"not null;default:0" json:"failure_count"`
	ExpiresAt    time.Time `gorm:"index;not null" json:"expires_at"`
}

type RevokedToken struct {
	TokenHash string    `gorm:"primaryKey;size:64" json:"-"`
	ExpiresAt time.Time `gorm:"index;not null" json:"expires_at"`
	CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}

type RolePermission struct {
	BaseModel
	RoleName  string `gorm:"column:role_name;size:20;not null;index:idx_role_perm" json:"role_name"`
	Module    string `gorm:"size:50;not null;index:idx_role_perm" json:"module"`
	CanView   bool   `gorm:"column:can_view;default:true" json:"can_view"`
	CanCreate bool   `gorm:"column:can_create;default:false" json:"can_create"`
	CanEdit   bool   `gorm:"column:can_edit;default:false" json:"can_edit"`
	CanDelete bool   `gorm:"column:can_delete;default:false" json:"can_delete"`
	CanExport bool   `gorm:"column:can_export;default:false" json:"can_export"`
}

type ActivityLog struct {
	BaseModel
	UserID    uint   `gorm:"not null;index" json:"user_id"`
	Username  string `gorm:"type:varchar(100)" json:"username"`
	Role      string `gorm:"type:varchar(20)" json:"role"`
	Module    string `gorm:"type:varchar(50)" json:"module"`
	Action    string `gorm:"type:longtext" json:"action"`
	Details   string `gorm:"type:longtext" json:"details"`
	OldValue  string `gorm:"type:longtext" json:"old_value"`
	NewValue  string `gorm:"type:longtext" json:"new_value"`
	IPAddress string `gorm:"column:ip_address;type:varchar(45)" json:"ip_address"`
	UserAgent string `gorm:"size:255" json:"user_agent"`
	BranchID  uint   `gorm:"index" json:"branch_id"`
}

type AuditLog struct {
	BaseModel
	UserID     uint   `gorm:"column:user_id;not null;default:0;index" json:"user_id"`
	Action     string `gorm:"column:action;size:20;not null;index" json:"action"`
	ModuleName string `gorm:"column:module_name;size:100;not null;index" json:"module_name"`
	Payload    string `gorm:"column:payload;type:longtext" json:"payload"`
}

// Service Authorization Memorandum Node
type ServiceAuthorization struct {
	BaseModel
	Ref            string    `gorm:"size:80;unique" json:"ref" validate:"required"`
	Date           time.Time `gorm:"type:date" json:"date"`
	RequestType    string    `gorm:"size:50;default:'repair'" json:"request_type"` // repair, calibration
	CustomerName   string    `gorm:"size:200" json:"customer_name" validate:"required"`
	JobName        string    `gorm:"size:200" json:"job_name"`  // e.g., Replace Part, Calibration
	Component      string    `gorm:"size:200" json:"component"` // e.g., 19x Injector PN 3609962
	EngineBrand    string    `gorm:"size:100" json:"engine_brand"`
	EngineModel    string    `gorm:"size:100" json:"engine_model"` // e.g., QSK60 G3
	ESN            string    `gorm:"size:100" json:"esn"`
	ToDepartment   string    `gorm:"size:150" json:"to_department"`
	FromDepartment string    `gorm:"size:150" json:"from_department"`
	SignedBy       string    `gorm:"size:150" json:"signed_by"`
	SignedTitle    string    `gorm:"size:100" json:"signed_title"`
	Status         string    `gorm:"size:20;not null;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived"`
	RevisionNumber int       `gorm:"default:0" json:"revision_number"`
	CreatedBy      *uint     `json:"created_by"`
	BranchID       uint      `gorm:"index" json:"branch_id"`
}

// ---------------------------------------------------------
// CUSTOMER PROFILE MODULE
// ---------------------------------------------------------

type CustomerProfile struct {
	BaseModel
	DocumentNumber   string `gorm:"column:document_number;type:varchar(20);not null;default:''" json:"document_number"`
	CustomerName     string `gorm:"column:customer_name;type:varchar(200);not null;unique" json:"customer_name" validate:"required"`
	BillingAddress   string `gorm:"column:billing_address;type:text;not null" json:"billing_address"`
	CityBilling      string `gorm:"column:city_billing;type:varchar(100);not null;default:''" json:"city_billing"`
	Telephone        string `gorm:"column:telephone;type:varchar(50);not null;default:''" json:"telephone"`
	Fax              string `gorm:"column:fax;type:varchar(50);not null;default:''" json:"fax"`
	PurchasingEmail  string `gorm:"column:purchasing_email;type:varchar(100);not null;default:''" json:"purchasing_email"`
	FinanceEmail     string `gorm:"column:finance_email;type:varchar(100);not null;default:''" json:"finance_email"`
	WapuStatus       bool   `gorm:"column:wapu_status;not null;default:false" json:"wapu_status"`
	DeliveryAddress  string `gorm:"column:delivery_address;type:text;not null" json:"delivery_address"`
	CityDelivery     string `gorm:"column:city_delivery;type:varchar(100);not null;default:''" json:"city_delivery"`
	Npwp             string `gorm:"column:npwp;type:varchar(50);not null;default:''" json:"npwp"`
	ParentCompany    string `gorm:"column:parent_company;type:varchar(200);not null;default:''" json:"parent_company"`
	NatureOfBusiness string `gorm:"column:nature_of_business;type:text;not null" json:"nature_of_business"`

	// Business Sectors
	CatAgriculture    bool `gorm:"column:cat_agriculture;not null;default:false" json:"cat_agriculture"`
	CatConstruction   bool `gorm:"column:cat_construction;not null;default:false" json:"cat_construction"`
	CatFinance        bool `gorm:"column:cat_finance;not null;default:false" json:"cat_finance"`
	CatIndustryMfg    bool `gorm:"column:cat_industry_mfg;not null;default:false" json:"cat_industry_mfg"`
	CatLogging        bool `gorm:"column:cat_logging;not null;default:false" json:"cat_logging"`
	CatMarineFishery  bool `gorm:"column:cat_marine_fishery;not null;default:false" json:"cat_marine_fishery"`
	CatMining         bool `gorm:"column:cat_mining;not null;default:false" json:"cat_mining"`
	CatOemDistributor bool `gorm:"column:cat_oem_distributor;not null;default:false" json:"cat_oem_distributor"`
	CatOilGas         bool `gorm:"column:cat_oil_gas;not null;default:false" json:"cat_oil_gas"`
	CatShipping       bool `gorm:"column:cat_shipping;not null;default:false" json:"cat_shipping"`
	CatPort           bool `gorm:"column:cat_port;not null;default:false" json:"cat_port"`
	CatProperty       bool `gorm:"column:cat_property;not null;default:false" json:"cat_property"`
	CatPublicUtility  bool `gorm:"column:cat_public_utility;not null;default:false" json:"cat_public_utility"`
	CatRail           bool `gorm:"column:cat_rail;not null;default:false" json:"cat_rail"`
	CatRental         bool `gorm:"column:cat_rental;not null;default:false" json:"cat_rental"`
	CatRetail         bool `gorm:"column:cat_retail;not null;default:false" json:"cat_retail"`
	CatTrader         bool `gorm:"column:cat_trader;not null;default:false" json:"cat_trader"`
	CatSupplier       bool `gorm:"column:cat_supplier;not null;default:false" json:"cat_supplier"`
	CatOthers         bool `gorm:"column:cat_others;not null;default:false" json:"cat_others"`

	Status   string `gorm:"column:status;type:varchar(20);not null;default:'draft'" json:"status" validate:"required,oneof=draft submitted approved rejected archived locked"`
	BranchID uint   `gorm:"index" json:"branch_id"`

	// Child Collections
	DecisionMakers []CustomerDecisionMaker `gorm:"foreignKey:UserProfileID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"decision_makers,omitempty"`
	Equipments     []CustomerEquipment     `gorm:"foreignKey:UserProfileID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"equipments,omitempty"`
	Affiliations   []CustomerAffiliation   `gorm:"foreignKey:UserProfileID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"affiliations,omitempty"`
}

type CustomerDecisionMaker struct {
	BaseModel
	UserProfileID uint   `gorm:"column:user_profile_id;not null;index" json:"user_profile_id"`
	Name          string `gorm:"column:name;type:varchar(150);not null;default:''" json:"name" validate:"required"`
	Position      string `gorm:"column:position;type:varchar(100);not null;default:''" json:"position"`
	ContactInfo   string `gorm:"column:contact_info;type:varchar(150);not null;default:''" json:"contact_info"`
	Level         string `gorm:"column:level;type:varchar(50);not null;default:''" json:"level"`
}

type CustomerEquipment struct {
	BaseModel
	UserProfileID uint       `gorm:"column:user_profile_id;not null;index" json:"user_profile_id"`
	EquipmentType string     `gorm:"column:equipment_type;type:varchar(20);not null;default:'altrak'" json:"equipment_type"`
	Brand         string     `gorm:"column:brand;type:varchar(100);not null;default:''" json:"brand"`
	Model         string     `gorm:"column:model;type:varchar(100);not null;default:''" json:"model"`
	MachineSN     string     `gorm:"column:machine_sn;type:varchar(100);not null;default:''" json:"machine_sn"`
	EngineModel   string     `gorm:"column:engine_model;type:varchar(100);not null;default:''" json:"engine_model"`
	EngineSN      string     `gorm:"column:engine_sn;type:varchar(100);not null;default:''" json:"engine_sn"`
	DeliveryDate  *time.Time `gorm:"column:delivery_date;type:date" json:"delivery_date"`
}

type CustomerAffiliation struct {
	BaseModel
	UserProfileID uint   `gorm:"column:user_profile_id;not null;index" json:"user_profile_id"`
	Name          string `gorm:"column:name;type:varchar(150);not null;default:''" json:"name" validate:"required"`
	Address       string `gorm:"column:address;type:text;not null" json:"address"`
}

// Background Job Intelligence Node
type BackgroundJob struct {
	BaseModel
	JobType      string     `gorm:"column:job_type;size:50;not null;index" json:"job_type"`      // e.g., "IMPORT_PSO", "BACKUP_DB"
	Status       string     `gorm:"column:status;size:20;default:'PENDING';index" json:"status"` // PENDING, PROCESSING, COMPLETED, FAILED
	Description  string     `gorm:"column:description;type:text" json:"description"`
	Progress     int        `gorm:"column:progress;default:0" json:"progress"` // 0-100
	TotalItems   int        `gorm:"column:total_items;default:0" json:"total_items"`
	Processed    int        `gorm:"column:processed;default:0" json:"processed"`
	ErrorMessage string     `gorm:"column:error_message;type:text" json:"error_message"`
	StartedAt    *time.Time `gorm:"column:started_at" json:"started_at"`
	CompletedAt  *time.Time `gorm:"column:completed_at" json:"completed_at"`
	CreatedBy    uint       `gorm:"column:created_by;index" json:"created_by"`
	BranchID     uint       `gorm:"column:branch_id;index" json:"branch_id"`
}
