package repository import ( "context" "crypto/rand" "database/sql" "encoding/hex" "fmt" "time" "github.com/google/uuid" ) type ShareLinkRepo struct { db *sql.DB } func NewShareLinkRepo(db *sql.DB) *ShareLinkRepo { return &ShareLinkRepo{db: db} } type ShareLink struct { ID string `json:"id"` Code string `json:"code"` CompanyID string `json:"company_id"` CreatedBy string `json:"created_by"` ResourceType string `json:"resource_type"` ResourceID string `json:"resource_id"` ExpiresAt *time.Time `json:"expires_at,omitempty"` CreatedAt time.Time `json:"created_at"` } func (r *ShareLinkRepo) Create(ctx context.Context, companyID, createdBy, resourceType, resourceID string, expiresAt *time.Time) (*ShareLink, error) { id := uuid.New().String() code := generateShortCode() _, err := r.db.ExecContext(ctx, `INSERT INTO ilm_share_link (id, code, company_id, created_by, resource_type, resource_id, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, id, code, companyID, createdBy, resourceType, resourceID, expiresAt, ) if err != nil { return nil, fmt.Errorf("create share link: %w", err) } return &ShareLink{ ID: id, Code: code, CompanyID: companyID, CreatedBy: createdBy, ResourceType: resourceType, ResourceID: resourceID, ExpiresAt: expiresAt, CreatedAt: time.Now(), }, nil } func (r *ShareLinkRepo) GetByCode(ctx context.Context, code string) (*ShareLink, error) { var sl ShareLink err := r.db.QueryRowContext(ctx, `SELECT id, code, company_id, created_by, resource_type, resource_id, expires_at, created_at FROM ilm_share_link WHERE code = ?`, code, ).Scan(&sl.ID, &sl.Code, &sl.CompanyID, &sl.CreatedBy, &sl.ResourceType, &sl.ResourceID, &sl.ExpiresAt, &sl.CreatedAt) if err == sql.ErrNoRows { return nil, nil } if err != nil { return nil, fmt.Errorf("get share link: %w", err) } return &sl, nil } func generateShortCode() string { b := make([]byte, 6) rand.Read(b) return hex.EncodeToString(b) }