package models

import (
	"database/sql/driver"
	"encoding/json"
	"time"
)

// UserCompany represents the N:M relationship between users and companies
type UserCompany struct {
	ID          string    `json:"id" db:"id"`
	UserID      string    `json:"userId" db:"user_id"`
	CompanyID   string    `json:"companyId" db:"company_id"`
	Role        string    `json:"role" db:"role"` // admin, recruiter
	Permissions JSONMap   `json:"permissions,omitempty" db:"permissions"`
	CreatedAt   time.Time `json:"createdAt" db:"created_at"`
}

// UserCompanyWithDetails includes user and company information
type UserCompanyWithDetails struct {
	UserCompany
	UserName    string `json:"userName,omitempty"`
	CompanyName string `json:"companyName,omitempty"`
}

// JSONMap is a custom type for JSONB fields
type JSONMap map[string]interface{}

// Value implements the driver.Valuer interface for JSON serialization
func (j JSONMap) Value() (driver.Value, error) {
	if j == nil {
		return nil, nil
	}
	return json.Marshal(j)
}

// Scan implements the sql.Scanner interface for JSON deserialization
func (j *JSONMap) Scan(value interface{}) error {
	if value == nil {
		*j = nil
		return nil
	}

	bytes, ok := value.([]byte)
	if !ok {
		return nil
	}

	return json.Unmarshal(bytes, j)
}
