package models

import (
	"time"

	"gorm.io/gorm"
)

type Project struct {
	ID        uint           `json:"id" gorm:"primaryKey"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`

	Name        string     `json:"name" gorm:"not null"`
	Description string     `json:"description"`
	Status      string     `json:"status" gorm:"default:'active'"` // active, completed, archived, on_hold
	StartDate   *time.Time `json:"start_date"`
	EndDate     *time.Time `json:"end_date"`
	Color       string     `json:"color" gorm:"default:'#3b82f6'"` // Hex color for UI

	// Foreign Keys
	OwnerID uint `json:"owner_id" gorm:"not null"`

	// Relationships
	Owner   User         `json:"owner" gorm:"foreignKey:OwnerID"`
	Members []User       `json:"members" gorm:"many2many:project_members"`
	Tasks   []Task       `json:"tasks" gorm:"foreignKey:ProjectID"`
	Files   []FileUpload `json:"files" gorm:"foreignKey:ProjectID"`
}

type ProjectMember struct {
	ID        uint           `json:"id" gorm:"primaryKey"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`

	ProjectID uint   `json:"project_id" gorm:"not null"`
	UserID    uint   `json:"user_id" gorm:"not null"`
	Role      string `json:"role" gorm:"default:'member'"` // owner, manager, member

	// Relationships
	Project Project `json:"project" gorm:"foreignKey:ProjectID"`
	User    User    `json:"user" gorm:"foreignKey:UserID"`
}

// IsOwner checks if the given user is the owner of this project
func (p *Project) IsOwner(userID uint) bool {
	return p.OwnerID == userID
}

// HasMember checks if the given user is a member of this project
func (p *Project) HasMember(userID uint) bool {
	for _, member := range p.Members {
		if member.ID == userID {
			return true
		}
	}
	return false
}

// GetMemberRole returns the role of a member in this project
func (p *Project) GetMemberRole(userID uint) string {
	if p.OwnerID == userID {
		return "owner"
	}

	for _, member := range p.Members {
		if member.ID == userID {
			// Get role from ProjectMember table
			var pm ProjectMember
			if err := db.Where("project_id = ? AND user_id = ?", p.ID, userID).First(&pm).Error; err == nil {
				return pm.Role
			}
			return "member"
		}
	}
	return ""
}
