package repositories import ( "context" "database/sql" "fmt" "strings" "thamanyah/cms/v2/internal/models" ) type VideoRepository struct { SQLDB *sql.DB } var VideoRepo VideoRepository func (svc VideoRepository) CreateVideo(ctx context.Context, v models.Video) (models.Video, error) { tx, err := svc.SQLDB.BeginTx(ctx, nil) if err != nil { return models.Video{}, err } defer tx.Rollback() row := tx.QueryRowContext(ctx, ` INSERT INTO videos (title, description, tags, file_name, storage_key, mediaconvert_job_id, status, size_bytes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, updated_at `, v.Title, v.Description, v.Tags, v.FileName, v.StorageKey, v.MediaConvertJobID, string(v.Status), v.SizeBytes) if err := row.Scan(&v.ID, &v.CreatedAt, &v.UpdatedAt); err != nil { return models.Video{}, err } rows := make([]string, 0, len(v.CategoryIDs)) for _, categoryID := range v.CategoryIDs { rows = append(rows, fmt.Sprintf("($1, %d)", categoryID)) } if _, err := tx.ExecContext(ctx, `INSERT INTO video_categories (video_id, category_id) VALUES `+strings.Join(rows, ", "), v.ID); err != nil { return models.Video{}, fmt.Errorf("linking categories %v: %w", v.CategoryIDs, err) } if err := tx.Commit(); err != nil { return models.Video{}, err } return v, nil }