package housing

import (
	"sync"
	"time"
)

// HouseZone represents a house type that can be purchased
type HouseZone struct {
	mu           sync.RWMutex
	ID           int32  `json:"id"`            // Unique house type identifier
	Name         string `json:"name"`          // House name/type
	ZoneID       int32  `json:"zone_id"`       // Zone where house is located
	CostCoin     int64  `json:"cost_coin"`     // Purchase cost in coins
	CostStatus   int64  `json:"cost_status"`   // Purchase cost in status points
	UpkeepCoin   int64  `json:"upkeep_coin"`   // Upkeep cost in coins
	UpkeepStatus int64  `json:"upkeep_status"` // Upkeep cost in status points
	Alignment    int8   `json:"alignment"`     // Alignment requirement
	GuildLevel   int8   `json:"guild_level"`   // Required guild level
	VaultSlots   int    `json:"vault_slots"`   // Number of vault storage slots
	MaxItems     int    `json:"max_items"`     // Maximum items that can be placed
	MaxVisitors  int    `json:"max_visitors"`  // Maximum concurrent visitors
	UpkeepPeriod int32  `json:"upkeep_period"` // Upkeep period in seconds
	Description  string `json:"description"`   // Description text
	SaveNeeded   bool   `json:"-"`             // Flag indicating if database save is needed
}

// PlayerHouse represents a house owned by a player
type PlayerHouse struct {
	mu           sync.RWMutex
	UniqueID     int64                 `json:"unique_id"`     // Database unique ID
	CharacterID  int32                 `json:"char_id"`       // Owner character ID
	HouseID      int32                 `json:"house_id"`      // House type ID
	InstanceID   int32                 `json:"instance_id"`   // Instance identifier
	UpkeepDue    time.Time             `json:"upkeep_due"`    // When upkeep is due
	EscrowCoins  int64                 `json:"escrow_coins"`  // Coins in escrow account
	EscrowStatus int64                 `json:"escrow_status"` // Status points in escrow
	PlayerName   string                `json:"player_name"`   // Owner's name
	Status       int8                  `json:"status"`        // House status
	Deposits     []HouseDeposit        `json:"deposits"`      // Deposit history
	History      []HouseHistory        `json:"history"`       // Transaction history
	AccessList   map[int32]HouseAccess `json:"access_list"`   // Player access permissions
	Amenities    []HouseAmenity        `json:"amenities"`     // Purchased amenities
	Items        []HouseItem           `json:"items"`         // Placed items
	Settings     HouseSettings         `json:"settings"`      // House settings
	SaveNeeded   bool                  `json:"-"`             // Flag indicating if database save is needed
}

// HouseDeposit represents a deposit transaction
type HouseDeposit struct {
	Timestamp   time.Time `json:"timestamp"`    // When deposit was made
	Amount      int64     `json:"amount"`       // Coin amount deposited
	LastAmount  int64     `json:"last_amount"`  // Previous coin amount
	Status      int64     `json:"status"`       // Status points deposited
	LastStatus  int64     `json:"last_status"`  // Previous status points
	Name        string    `json:"name"`         // Player who made deposit
	CharacterID int32     `json:"character_id"` // Character ID who made deposit
}

// HouseHistory represents a house transaction history entry
type HouseHistory struct {
	Timestamp   time.Time `json:"timestamp"`    // When transaction occurred
	Amount      int64     `json:"amount"`       // Coin amount involved
	Status      int64     `json:"status"`       // Status points involved
	Reason      string    `json:"reason"`       // Reason for transaction
	Name        string    `json:"name"`         // Player involved
	CharacterID int32     `json:"character_id"` // Character ID involved
	PosFlag     int8      `json:"pos_flag"`     // Positive/negative transaction
	Type        int       `json:"type"`         // Transaction type
}

// HouseAccess represents access permissions for a player
type HouseAccess struct {
	CharacterID int32     `json:"character_id"` // Character being granted access
	PlayerName  string    `json:"player_name"`  // Player name
	AccessLevel int8      `json:"access_level"` // Access level
	Permissions int32     `json:"permissions"`  // Permission flags
	GrantedBy   int32     `json:"granted_by"`   // Who granted the access
	GrantedDate time.Time `json:"granted_date"` // When access was granted
	ExpiresDate time.Time `json:"expires_date"` // When access expires (0 = never)
	Notes       string    `json:"notes"`        // Optional notes
}

// HouseAmenity represents a purchased house amenity
type HouseAmenity struct {
	ID           int32     `json:"id"`            // Amenity ID
	Type         int       `json:"type"`          // Amenity type
	Name         string    `json:"name"`          // Amenity name
	Cost         int64     `json:"cost"`          // Purchase cost
	StatusCost   int64     `json:"status_cost"`   // Status cost
	PurchaseDate time.Time `json:"purchase_date"` // When purchased
	X            float32   `json:"x"`             // X position
	Y            float32   `json:"y"`             // Y position
	Z            float32   `json:"z"`             // Z position
	Heading      float32   `json:"heading"`       // Heading
	IsActive     bool      `json:"is_active"`     // Whether amenity is active
}

// HouseItem represents an item placed in a house
type HouseItem struct {
	ID          int64     `json:"id"`           // Item unique ID
	ItemID      int32     `json:"item_id"`      // Item template ID
	CharacterID int32     `json:"character_id"` // Who placed the item
	X           float32   `json:"x"`            // X position
	Y           float32   `json:"y"`            // Y position
	Z           float32   `json:"z"`            // Z position
	Heading     float32   `json:"heading"`      // Heading
	PitchX      float32   `json:"pitch_x"`      // Pitch X
	PitchY      float32   `json:"pitch_y"`      // Pitch Y
	RollX       float32   `json:"roll_x"`       // Roll X
	RollY       float32   `json:"roll_y"`       // Roll Y
	PlacedDate  time.Time `json:"placed_date"`  // When item was placed
	Quantity    int32     `json:"quantity"`     // Item quantity
	Condition   int8      `json:"condition"`    // Item condition
	House       string    `json:"house"`        // House identifier
}

// HouseSettings represents house configuration settings
type HouseSettings struct {
	HouseName       string `json:"house_name"`        // Custom house name
	VisitPermission int8   `json:"visit_permission"`  // Who can visit
	PublicNote      string `json:"public_note"`       // Public note displayed
	PrivateNote     string `json:"private_note"`      // Private note for owner
	AllowFriends    bool   `json:"allow_friends"`     // Allow friends to visit
	AllowGuild      bool   `json:"allow_guild"`       // Allow guild members to visit
	RequireApproval bool   `json:"require_approval"`  // Require approval for visits
	ShowOnDirectory bool   `json:"show_on_directory"` // Show in house directory
	AllowDecoration bool   `json:"allow_decoration"`  // Allow others to decorate
	TaxExempt       bool   `json:"tax_exempt"`        // Tax exemption status
}

// HousingManager manages the overall housing system
type HousingManager struct {
	mu              sync.RWMutex
	houseZones      map[int32]*HouseZone             // Available house types
	playerHouses    map[int64]*PlayerHouse           // All player houses by unique ID
	characterHouses map[int32][]*PlayerHouse         // Houses by character ID
	zoneInstances   map[int32]map[int32]*PlayerHouse // Houses by zone and instance
	database        HousingDatabase
	clientManager   ClientManager
	playerManager   PlayerManager
	itemManager     ItemManager
	zoneManager     ZoneManager
	eventHandler    HousingEventHandler
	logger          LogHandler
	// Configuration
	enableUpkeep       bool
	enableForeclosure  bool
	upkeepGracePeriod  int32
	maxHousesPerPlayer int
	enableStatistics   bool
}

// HousingStatistics tracks housing system usage
type HousingStatistics struct {
	TotalHouses          int64            `json:"total_houses"`
	ActiveHouses         int64            `json:"active_houses"`
	ForelosedHouses      int64            `json:"foreclosed_houses"`
	TotalDeposits        int64            `json:"total_deposits"`
	TotalWithdrawals     int64            `json:"total_withdrawals"`
	AverageUpkeepPaid    float64          `json:"average_upkeep_paid"`
	MostPopularHouseType int32            `json:"most_popular_house_type"`
	HousesByType         map[int32]int64  `json:"houses_by_type"`
	HousesByAlignment    map[int8]int64   `json:"houses_by_alignment"`
	RevenueByType        map[int]int64    `json:"revenue_by_type"`
	TopDepositors        []PlayerDeposits `json:"top_depositors"`
}

// PlayerDeposits tracks deposits by player
type PlayerDeposits struct {
	CharacterID   int32  `json:"character_id"`
	PlayerName    string `json:"player_name"`
	TotalDeposits int64  `json:"total_deposits"`
	HouseCount    int    `json:"house_count"`
}

// HousingSearchCriteria for searching houses
type HousingSearchCriteria struct {
	OwnerName     string `json:"owner_name"`      // Filter by owner name
	HouseType     int32  `json:"house_type"`      // Filter by house type
	Alignment     int8   `json:"alignment"`       // Filter by alignment
	MinCost       int64  `json:"min_cost"`        // Minimum cost filter
	MaxCost       int64  `json:"max_cost"`        // Maximum cost filter
	Zone          int32  `json:"zone"`            // Filter by zone
	VisitableOnly bool   `json:"visitable_only"`  // Only houses that can be visited
	PublicOnly    bool   `json:"public_only"`     // Only publicly accessible houses
	NamePattern   string `json:"name_pattern"`    // Filter by house name pattern
	HasAmenities  bool   `json:"has_amenities"`   // Filter houses with amenities
	MinVaultSlots int    `json:"min_vault_slots"` // Minimum vault slots
}

// Database record types for data persistence

// HouseZoneData represents database record for house zones
type HouseZoneData struct {
	ID           int32  `json:"id"`
	Name         string `json:"name"`
	ZoneID       int32  `json:"zone_id"`
	CostCoin     int64  `json:"cost_coin"`
	CostStatus   int64  `json:"cost_status"`
	UpkeepCoin   int64  `json:"upkeep_coin"`
	UpkeepStatus int64  `json:"upkeep_status"`
	Alignment    int8   `json:"alignment"`
	GuildLevel   int8   `json:"guild_level"`
	VaultSlots   int    `json:"vault_slots"`
	MaxItems     int    `json:"max_items"`
	MaxVisitors  int    `json:"max_visitors"`
	UpkeepPeriod int32  `json:"upkeep_period"`
	Description  string `json:"description"`
}

// PlayerHouseData represents database record for player houses
type PlayerHouseData struct {
	UniqueID        int64     `json:"unique_id"`
	CharacterID     int32     `json:"char_id"`
	HouseID         int32     `json:"house_id"`
	InstanceID      int32     `json:"instance_id"`
	UpkeepDue       time.Time `json:"upkeep_due"`
	EscrowCoins     int64     `json:"escrow_coins"`
	EscrowStatus    int64     `json:"escrow_status"`
	Status          int8      `json:"status"`
	HouseName       string    `json:"house_name"`
	VisitPermission int8      `json:"visit_permission"`
	PublicNote      string    `json:"public_note"`
	PrivateNote     string    `json:"private_note"`
	AllowFriends    bool      `json:"allow_friends"`
	AllowGuild      bool      `json:"allow_guild"`
	RequireApproval bool      `json:"require_approval"`
	ShowOnDirectory bool      `json:"show_on_directory"`
	AllowDecoration bool      `json:"allow_decoration"`
	TaxExempt       bool      `json:"tax_exempt"`
}

// HouseDepositData represents database record for deposits
type HouseDepositData struct {
	HouseID     int64     `json:"house_id"`
	Timestamp   time.Time `json:"timestamp"`
	Amount      int64     `json:"amount"`
	LastAmount  int64     `json:"last_amount"`
	Status      int64     `json:"status"`
	LastStatus  int64     `json:"last_status"`
	Name        string    `json:"name"`
	CharacterID int32     `json:"character_id"`
}

// HouseHistoryData represents database record for house history
type HouseHistoryData struct {
	HouseID     int64     `json:"house_id"`
	Timestamp   time.Time `json:"timestamp"`
	Amount      int64     `json:"amount"`
	Status      int64     `json:"status"`
	Reason      string    `json:"reason"`
	Name        string    `json:"name"`
	CharacterID int32     `json:"character_id"`
	PosFlag     int8      `json:"pos_flag"`
	Type        int       `json:"type"`
}

// HouseAccessData represents database record for house access
type HouseAccessData struct {
	HouseID     int64     `json:"house_id"`
	CharacterID int32     `json:"character_id"`
	PlayerName  string    `json:"player_name"`
	AccessLevel int8      `json:"access_level"`
	Permissions int32     `json:"permissions"`
	GrantedBy   int32     `json:"granted_by"`
	GrantedDate time.Time `json:"granted_date"`
	ExpiresDate time.Time `json:"expires_date"`
	Notes       string    `json:"notes"`
}

// HouseAmenityData represents database record for house amenities
type HouseAmenityData struct {
	HouseID      int64     `json:"house_id"`
	ID           int32     `json:"id"`
	Type         int       `json:"type"`
	Name         string    `json:"name"`
	Cost         int64     `json:"cost"`
	StatusCost   int64     `json:"status_cost"`
	PurchaseDate time.Time `json:"purchase_date"`
	X            float32   `json:"x"`
	Y            float32   `json:"y"`
	Z            float32   `json:"z"`
	Heading      float32   `json:"heading"`
	IsActive     bool      `json:"is_active"`
}

// HouseItemData represents database record for house items
type HouseItemData struct {
	HouseID     int64     `json:"house_id"`
	ID          int64     `json:"id"`
	ItemID      int32     `json:"item_id"`
	CharacterID int32     `json:"character_id"`
	X           float32   `json:"x"`
	Y           float32   `json:"y"`
	Z           float32   `json:"z"`
	Heading     float32   `json:"heading"`
	PitchX      float32   `json:"pitch_x"`
	PitchY      float32   `json:"pitch_y"`
	RollX       float32   `json:"roll_x"`
	RollY       float32   `json:"roll_y"`
	PlacedDate  time.Time `json:"placed_date"`
	Quantity    int32     `json:"quantity"`
	Condition   int8      `json:"condition"`
	House       string    `json:"house"`
}

// PacketData structures for client communication

// HousePurchasePacketData represents data for house purchase UI
type HousePurchasePacketData struct {
	HouseID      int32  `json:"house_id"`
	Name         string `json:"name"`
	CostCoin     int64  `json:"cost_coin"`
	CostStatus   int64  `json:"cost_status"`
	UpkeepCoin   int64  `json:"upkeep_coin"`
	UpkeepStatus int64  `json:"upkeep_status"`
	Alignment    int8   `json:"alignment"`
	GuildLevel   int8   `json:"guild_level"`
	VaultSlots   int    `json:"vault_slots"`
	Description  string `json:"description"`
}

// HouseListPacketData represents data for housing list UI
type HouseListPacketData struct {
	Houses []PlayerHouseInfo `json:"houses"`
}

// PlayerHouseInfo represents house info for list display
type PlayerHouseInfo struct {
	UniqueID     int64     `json:"unique_id"`
	Name         string    `json:"name"`
	HouseType    string    `json:"house_type"`
	UpkeepDue    time.Time `json:"upkeep_due"`
	EscrowCoins  int64     `json:"escrow_coins"`
	EscrowStatus int64     `json:"escrow_status"`
	Status       int8      `json:"status"`
	CanEnter     bool      `json:"can_enter"`
}

// BaseHouseWindowPacketData represents data for main house management UI
type BaseHouseWindowPacketData struct {
	HouseInfo      PlayerHouseInfo `json:"house_info"`
	RecentDeposits []HouseDeposit  `json:"recent_deposits"`
	RecentHistory  []HouseHistory  `json:"recent_history"`
	Amenities      []HouseAmenity  `json:"amenities"`
	Settings       HouseSettings   `json:"settings"`
	CanManage      bool            `json:"can_manage"`
}

// HouseVisitPacketData represents data for house visit UI
type HouseVisitPacketData struct {
	AvailableHouses []VisitableHouse `json:"available_houses"`
}

// VisitableHouse represents a house that can be visited
type VisitableHouse struct {
	UniqueID         int64  `json:"unique_id"`
	OwnerName        string `json:"owner_name"`
	HouseName        string `json:"house_name"`
	HouseType        string `json:"house_type"`
	PublicNote       string `json:"public_note"`
	CanVisit         bool   `json:"can_visit"`
	RequiresApproval bool   `json:"requires_approval"`
}

// Event structures for housing system events

// HousingEvent represents a housing system event
type HousingEvent struct {
	ID          int64     `json:"id"`
	HouseID     int64     `json:"house_id"`
	EventType   int       `json:"event_type"`
	CharacterID int32     `json:"character_id"`
	Timestamp   time.Time `json:"timestamp"`
	Data        string    `json:"data"`
}

// Configuration structure for housing system
type HousingConfig struct {
	EnableUpkeep            bool  `json:"enable_upkeep"`
	EnableForeclosure       bool  `json:"enable_foreclosure"`
	UpkeepGracePeriod       int32 `json:"upkeep_grace_period"` // seconds
	MaxHousesPerPlayer      int   `json:"max_houses_per_player"`
	EnableStatistics        bool  `json:"enable_statistics"`
	AutoCleanupInterval     int32 `json:"auto_cleanup_interval"` // seconds
	MaxHistoryEntries       int   `json:"max_history_entries"`
	MaxDepositEntries       int   `json:"max_deposit_entries"`
	DefaultInstanceLifetime int32 `json:"default_instance_lifetime"` // seconds
}
